从 *ngFor 中的 select 个元素获取值
Getting values from select elements in *ngFor
假设我有这个模板:
<div *ngFor="let div of divs">
<select #ref (change)="print(ref)">
<option *ngFor = "let opt of options">{{opt}}</option>
</select>
</div>
和这个组件:
export class AppComponent {
divs = ["1", "2", "3"];
options = ["opt1", "opt2", "opt3"];
print(value){
console.log(value.value);
};
}
现在,只要 select 编辑了新选项,我就可以获取每个 select 元素的值。但是,使用这种方法,我在 *ngFor
循环中的 select (#ref
) 上创建了一个 template reference variable
,这意味着我将有 3 个 select在循环结束时使用相同的引用。它在 angular.io 网站上说了以下内容:
"Do not define the same variable name more than once in the same template. The runtime value will be unpredictable."
因此,我认为使用此方法不是个好主意。我的问题是是否有另一种方法可以做到这一点?
我不认为,只需要局部变量来获取选定的值:
只需使用 (change)="print($event.target.value)"
和 [value]='opt'
<div *ngFor="let div of divs">
<select (change)="print(div ,$event.target.value)">
<option *ngFor = "let opt of options" [value]='opt'>{{opt}}</option>
</select>
</div>
print(value_of , value) {
console.log('value of' , value_of , 'is' , value );
}
假设我有这个模板:
<div *ngFor="let div of divs">
<select #ref (change)="print(ref)">
<option *ngFor = "let opt of options">{{opt}}</option>
</select>
</div>
和这个组件:
export class AppComponent {
divs = ["1", "2", "3"];
options = ["opt1", "opt2", "opt3"];
print(value){
console.log(value.value);
};
}
现在,只要 select 编辑了新选项,我就可以获取每个 select 元素的值。但是,使用这种方法,我在 *ngFor
循环中的 select (#ref
) 上创建了一个 template reference variable
,这意味着我将有 3 个 select在循环结束时使用相同的引用。它在 angular.io 网站上说了以下内容:
"Do not define the same variable name more than once in the same template. The runtime value will be unpredictable."
因此,我认为使用此方法不是个好主意。我的问题是是否有另一种方法可以做到这一点?
我不认为,只需要局部变量来获取选定的值:
只需使用 (change)="print($event.target.value)"
和 [value]='opt'
<div *ngFor="let div of divs">
<select (change)="print(div ,$event.target.value)">
<option *ngFor = "let opt of options" [value]='opt'>{{opt}}</option>
</select>
</div>
print(value_of , value) {
console.log('value of' , value_of , 'is' , value );
}