使用 Angular 6 选择下拉列表的默认值



我有一个选择输入:

<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内有他的价值

我尝试用以下方法预先选择它:

[selected]="championship.settings.fightDuration==duration"

我在选择文本中,我打印了这个条件的结果,它在与值匹配的元素上打印true,所以它应该可以工作,但选择没有选择的值......

我错过了什么?

如果有人在选择默认值时仍然遇到问题,请尝试此操作。

假设您希望选择的选项具有值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'}
];
}

提交时

在您的提交函数中,只需像这样调用即可获取所选值。

this.someModel

希望这对某人有所帮助。

这个视频对我有帮助 - https://www.youtube.com/watch?v=8ZlrORYOl_0

你可以按如下方式使用[ngValue]

<option *ngFor="let duration of durations" [ngValue]="duration"> 
{{ duration }} {{ championship.settings.fightDuration==duration }}
</option>

堆叠闪电战的工作示例

最新更新