首页 > 解决方案 > 如何使用Angular 8中的模板引用为输入文本字段赋值

问题描述

我有下拉更改事件,在更改事件期间,我需要为相应的文本字段填充一些值。

app.component.html

<tr>
  <td>John</td>
  <td>
    <select (change)="editAge(selectField1.value, 1)" #selectField1>
      <option value="1">Less than 10</option>
      <option value="2">Greater than 10 and Less than 80</option>
      <option value="3">Less than 80</option>
    </select>
  </td>
  <td>
    <span *ngIf="!(selectField1.value == 2)">24</span>
    <span *ngIf="selectField1.value == 2">
      <input type="text" #textField1/>
    </span>
  </td>
</tr>
<tr>
  <td>Jacky</td>
  <td>
    <select (change)="editAge(selectField2.value, 2)" #selectField2>
      <option value="1">Less than 10</option>
      <option value="2">Greater than 10 and Less than 80</option>
      <option value="3">Less than 80</option>
    </select>
  </td>
  <td>
    <span *ngIf="!(selectField2.value == 2)">4</span>
    <span *ngIf="selectField2.value == 2">
      <input type="text" #textField2 />
    </span>
  </td>
</tr>

app.component.ts

  expression = false;
  nameBind: string;
  @ViewChild('textField') nameInputRef: ElementRef;
  editAge(ee, i) {
    this.nameInputRef.nativeElement.value = 'Apple';
  }

在更改事件期间,editAge我需要更新相应的行文本字段。如何获取动态输入模板并更新?

例子

标签: javascripthtmlangular

解决方案


由于您需要更改行的每一列的输入。最好通过模型而不是 html 元素引用来处理它。

<table border="1">
  <tr><td>Name</td><td>Age</td><td>New Age</td></tr>
  <tr *ngFor="let cust of data; let j = index;"><td>{{cust.name}}</td><td>
    <select (change)="editAge(cust.age, j)" 
    [(ngModel)]="cust.age"
    #selectField1>
    <option [value]="i+1" *ngFor="let age of dropdownList; let i = index;">{{age.label}}</option>
  </select></td><td> <span  *ngIf="!(selectField1.value == 2)">{{cust.newAge}}</span> <span *ngIf="selectField1.value == 2"><input type="text" [(ngModel)]="cust.newAge" #textField/></span></td></tr>
</table>

dropdownList: any = [
    { label: 'Less than 10', newAge: '' },
    { label: 'Greater than 10 and Less than 80', newAge: 'Apple' },
    { label: 'Less than 80', newAge: 'Banana' }
  ];

  data: any = [
    { name: 'John', age: '1', newAge: '24' },
    { name: 'Jacky', age: '1', newAge: '4' },
    { name: 'Roy', age: '1', newAge: '34' }
  ]
  editAge(ee, i) {
    this.data[i].newAge = this.dropdownList[ee-1].newAge;
  }

查看此演示https://stackblitz.com/edit/angular-styrlp并让我知道它是否解决了。

更新(动态文本字段)

@ViewChild('textField1', { static: false }) nameInputRef1: ElementRef;
  @ViewChild('textField2', { static: false }) nameInputRef2: ElementRef;
  @ViewChild('textField3', { static: false }) nameInputRef3: ElementRef;

editAge(ee, i) {
    let elementRef = `nameInputRef${i}`;
    setTimeout(() => {
        console.log(this);

        if (this[elementRef])
        this[elementRef].nativeElement.value = 'Apple';
    }, 100);
  }

这是演示 - https://stackblitz.com/edit/angular-g3tzmh


推荐阅读