我有下拉更改事件,在更改事件中,我需要在相应的文本字段中填充一些值。
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
期间,我需要更新相应的行文本字段。如何获取动态输入模板并进行更新?
答案 0 :(得分:0)
因为您需要更改行每一列的输入。最好通过模型而不是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);
}