2017-09-25 60 views
-1

我使用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); 

    } 
+0

在编译时或在控制台上的任何错误? –

+0

编译或控制台中没有错误。每次获得第一个元素,如果点击另一个。 –

+0

添加完整的代码 –

回答

-1

您可以在编辑功能

<span class="icon-edit" id="i" #editIc (click)="edit(i)" ></span> 
//or 
<span class="icon-edit" id="i" #editIc (click)="edit(serviceDetail)" ></span> 
0

传递参数,你可以简单地传递$事件对象到函数。在$ 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); 
} 
0

使用*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; 

DEMO