角4 - 没有得到当前元素
问题描述:
我使用ngFor
来呈现数据,现在我想单击编辑图标来显示div,但我无法获取当前元素。角4 - 没有得到当前元素
<tr *ngFor="let serviceDetail of serviceDetailsList; let i = index">
<td>{{serviceDetail.serviceName}}</td>
<td>{{serviceDetail.serviceVersion}}</td>
<td>{{serviceDetail.isLatest}}</td>
<td>
<div class="showUrl" >
<span class="icon-edit" id="i" #editIc (click)="edit()" ></span>
</div>
<div class="editUrl" id="show" style="display: none">
<input type="text" name="" class="editUrl" #myInputText>
<a style="margin: 0 10px;" (click)="sendToServer('save')">Save</a>
<a class="urlClass" (click)="sendToServer()">Cancel</a>
</div>
</td>
</tr>
@ViewChild('editIc') editIc:ElementRef;
edit(){
let thisPElem = this.editIc.nativeElement.parentElement;
let thisPSibling = thisPElem.nextElementSibling;
thisPElem.style.display = 'none';
thisPSibling.style.display = 'block';
console.log(thisPElem);
}
答
您可以在编辑功能
<span class="icon-edit" id="i" #editIc (click)="edit(i)" ></span>
//or
<span class="icon-edit" id="i" #editIc (click)="edit(serviceDetail)" ></span>
答
传递参数,你可以简单地传递$事件对象到函数。在$ event对象中,您可以通过访问属性来查找元素。
<tr *ngFor="let serviceDetail of serviceDetailsList; let i = index">
<td>{{serviceDetail.serviceName}}</td>
<td>{{serviceDetail.serviceVersion}}</td>
<td>{{serviceDetail.isLatest}}</td>
<td>
<div class="showUrl" >
<span class="icon-edit" id="i" #editIc (click)="edit($event)" ></span>
</div>
<div class="editUrl" id="show" style="display: none">
<input type="text" name="" class="editUrl" #myInputText>
<a style="margin: 0 10px;" (click)="sendToServer('save')">Save</a>
<a class="urlClass" (click)="sendToServer()">Cancel</a>
</div>
</td>
</tr>
// function in your class
edit($event){
let thisPElem = $event.target;
let thisPSibling = thisPElem.nextSibling;
thisPElem.style.display = 'none';
thisPSibling.style.display = 'block';
console.log(thisPElem);
}
答
使用*ngIf
,它会显示/隐藏div。保留一个物业的状态(例如edit
波纹管)。它将保持行索引值。将它设置为-1返回。
HTML:
<div class="showUrl" *ngIf="edit !== i">
<span class="icon-edit" id="i" #editIc (click)="edit=i" ></span>
</div>
<div class="editUrl" *ngIf="edit === i" id="show">
<input type="text" name="" class="editUrl" #myInputText>
<a style="margin: 0 10px;" (click)="sendToServer('save');edit = -1">Save</a>
<a class="urlClass" (click)="sendToServer();edit = -1">Cancel</a>
</div>
TyepScript:
edit = -1;
在编译时或在控制台上的任何错误? –
编译或控制台中没有错误。每次获得第一个元素,如果点击另一个。 –
添加完整的代码 –