Angular 4 - 没有获得当前元素

时间:2017-09-25 06:34:01

标签: javascript angular typescript

我正在使用ngFor来渲染数据,现在我想在点击编辑图标时显示div,但我无法获取当前元素。

<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);

  }

3 个答案:

答案 0 :(得分:0)

您只需将$ event对象传递给函数即可。在$ 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);
}

答案 1 :(得分: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

答案 2 :(得分:-1)

你可以在编辑功能中传递参数

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