Select 下拉菜单的默认值 Angular 6
default value for Select dropdown with Angular 6
我有一个 select 输入:
<select id="duration" name="duration" class="form-control select-lg"
[(ngModel)]="championship.settings.fightDuration">
<option *ngFor="let duration of durations"
[selected]="championship.settings.fightDuration==duration">
{{ duration }} {{ championship.settings.fightDuration==duration }}
</option>
</select>
我有他的价值championship.settings.fightDuration
我尝试预先select它:
[selected]="championship.settings.fightDuration==duration"
I 在 select 文本中,我打印了这个条件的结果,它在匹配值的元素上打印了 true
,所以它应该可以工作,但是 select 有没有 selected 值...
我错过了什么?
您可以使用[ngValue]
如下
<option *ngFor="let duration of durations" [ngValue]="duration">
{{ duration }} {{ championship.settings.fightDuration==duration }}
</option>
上的工作示例
如果有人仍然遇到问题select尝试使用默认值。
假设您希望 select 的选项的值为 duration
。我假设这个选项已经在 items
数组中。
HTML
<select name="someName" [(ngModel)]="someModel">
<option *ngFor="let key of items" [value]="key.value">{{ key.label }}</option>
</select>
TS
class someComponent Implements OnInit {
someModel;
ngOnInit() {
this.someModel = 'duration';
this.items = [
{value: 'duration', label : 'Duration'},
{value: 'other', label : 'Other'},
{value: 'someOther', label : 'Some Other'}
];
}
提交时
在您的提交函数中,只需像这样调用即可获得 selected 值。
this.someModel
希望这对某人有所帮助。
虽然这个视频对我有帮助 - https://www.youtube.com/watch?v=8ZlrORYOl_0
我有一个 select 输入:
<select id="duration" name="duration" class="form-control select-lg"
[(ngModel)]="championship.settings.fightDuration">
<option *ngFor="let duration of durations"
[selected]="championship.settings.fightDuration==duration">
{{ duration }} {{ championship.settings.fightDuration==duration }}
</option>
</select>
我有他的价值championship.settings.fightDuration
我尝试预先select它:
[selected]="championship.settings.fightDuration==duration"
I 在 select 文本中,我打印了这个条件的结果,它在匹配值的元素上打印了 true
,所以它应该可以工作,但是 select 有没有 selected 值...
我错过了什么?
您可以使用[ngValue]
如下
<option *ngFor="let duration of durations" [ngValue]="duration">
{{ duration }} {{ championship.settings.fightDuration==duration }}
</option>
上的工作示例
如果有人仍然遇到问题select尝试使用默认值。
假设您希望 select 的选项的值为 duration
。我假设这个选项已经在 items
数组中。
HTML
<select name="someName" [(ngModel)]="someModel">
<option *ngFor="let key of items" [value]="key.value">{{ key.label }}</option>
</select>
TS
class someComponent Implements OnInit {
someModel;
ngOnInit() {
this.someModel = 'duration';
this.items = [
{value: 'duration', label : 'Duration'},
{value: 'other', label : 'Other'},
{value: 'someOther', label : 'Some Other'}
];
}
提交时
在您的提交函数中,只需像这样调用即可获得 selected 值。
this.someModel
希望这对某人有所帮助。
虽然这个视频对我有帮助 - https://www.youtube.com/watch?v=8ZlrORYOl_0