set下拉选择选项为迭代前的默认选择

set下拉选择选项为迭代前的默认选择

本文介绍了Angular set下拉选择选项为迭代前的默认选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个选择下拉菜单,并且从列表中迭代了这些选项.如果用户未选择值,我试图将一个单独的选项设置为默认(默认).

I have a select dropdown and I iterate the options from a list. I am trying to set as selected a separate option (as a default), in case of user is not selecting a value.

这是我尝试实现的方式:

Here is how I am trying to implement that:

<select [(ngModel)]="book.pageLayout">
    <option [value]="0" [attr.selected]="book.defaultLayoutId === null">No Default Layout</option>
    <option *ngFor="let l of availableLayouts"
            [value]="l.id"
            [attr.selected]="book.pageLayout == l.id">
      {{l?.name}}
    </option>
  </select>

我也尝试过:

<option [value]="0" selected="selected">No Default Layout</option>

甚至:

<option [value]="0" selected="1==1">No Default Layout</option>

但以上方法均无效.

欢迎任何帮助

推荐答案

如果您使用的是ngModel,则选择的属性将无济于事,那么您可以轻松地将默认值设置为已定义的模型.

Attribute selected will not help much if you are using ngModel then you can do easily with setting default value to the defined model.

<select [(ngModel)]="book.pageLayout">
  <option value="">No Default Layout</option>
  <option *ngFor="let l of availableLayouts" [value]="l.id">
    {{l?.name}}
  </option>
</select>

然后在component.ts内部

Then inside component.ts

public book: any = {
   pageLayout: ''
}

修改

要设置默认选项,我们需要将pageLayout值设置为id而不是空字符串.

To set default option we need to set pageLayout value to id instead of empty string.

public book: any = {
   pageLayout: 1
}

public availableLayouts: any = [
  {
    name: "One",
    id: 1
  },
  {
    name: "Two",
    id: 2
  }
]

这篇关于Angular set下拉选择选项为迭代前的默认选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 13:26