Angular Anuglar,关注动态显示的输入

Angular Anuglar,关注动态显示的输入,angular,input,Angular,Input,我有一个组件,在通过循环添加的元素中显示/隐藏输入: <div *ngFor="item of items"> <div class="container"> <div *ngIf="selectedItem !== item.id"> <p>{{item.name}}</p><span (click)="showInput(item.id)">edit</span> </d

我有一个组件,在通过循环添加的元素中显示/隐藏输入:

<div *ngFor="item of items">
  <div class="container">
    <div *ngIf="selectedItem !== item.id">
      <p>{{item.name}}</p><span (click)="showInput(item.id)">edit</span>
    </div>

    <div *ngIf="selectedItem === item.id">
      <p><input type="text" [value]="item.name" /></p><span (click)="hideInput()">edit</span>
    </div>
  </div>
</div>

selectedItem: string;
...
showInput(id: string) {
  this.selectedItem = id;
}

hideInput() {
  this.selectedItem = null;
}

{{item.name}}

编辑

编辑 selectedItem:string; ... showInput(id:字符串){ this.selectedItem=id; } hideInput(){ this.selectedItem=null; }
我尝试对输入使用
@ViewChild
,但如果在
ngIf
中,它返回
未定义的
。在输入上设置
autofocus
第一次起作用,但一旦显示/隐藏不止一次,它就会停止工作。

我创建了一个在单击“编辑”后聚焦输入元素的对话框

autofocus
属性只工作一次,因为它用于页面加载。查看此以了解更多信息