javascript - 如何使用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
我需要更新相应的行文本字段。如何获取动态输入模板并更新?
解决方案
由于您需要更改行的每一列的输入。最好通过模型而不是 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);
}
推荐阅读
- c# - 如何在c#中将空数据表导出到excel?
- javascript - 使用 javaScript 复制时,div 之间的 line-height 不同
- python - sklearn.transform 和 sklearn.fit_transform 给出不同的结果
- typescript - 打字稿编译器允许重复类型声明
- ios - 圆形条形图
- python-3.x - 添加、复制和创建新的 csv 文件
- json - 如何在没有 java 对象的情况下生成 JSON Schema
- python - 我有一个代码,它有一个不断重复的分数计数器
- serialization - 从字符串层次对象访问对象
- javascript - KnockoutJS ArrayFirst 无法按预期工作