首页 > 解决方案 > 使用 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在与值匹配的元素上,因此它应该可以工作,但是选择没有选定的值...

我错过了什么?

标签: angularangular6

解决方案


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

假设您希望选择的选项具有 value 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


推荐阅读