Angular 2:如何根据条件在选择中进行选择?

时间:2016-08-24 12:42:26

标签: angular

我从一个对象数组中构建一个表单中的select元素。我希望根据当前对象的属性( $("a:contains('Gmail')").trigger('click'); )选择其中一个选项。

基本模板代码如下所示:

myobject.is_default

我现在可以像这样设置选择选项:

<select formControlName="template">
  <option *ngFor="let t of templates" [value]="t.id">{{t.title}}</option>
</select>

但我遇到的问题是HTML5规范说明:

  

所选属性是布尔属性。

     

http://www.w3.org/TR/html5/infrastructure.html#boolean-attributes

     

元素上存在布尔属性表示true   value,缺少属性表示false值。

     

如果属性存在,则其值必须为空字符串   或者是属性的ASCII不区分大小写的匹配值   规范名称,没有前导或尾随空格。

以下是有效,等效和真实的:

<select formControlName="template">
  <option *ngFor="let t of templates" [value]="t.id" [selected]="t.is_default ? 'selected' : ''">{{t.title}}</option>
</select>

以下内容无效:

<option selected />
<option selected="" />
<option selected="selected" />
<option selected="SeLeCtEd" />

这意味着:只要存在所选属性,就会选择该选项。所以我需要一种方法,除了一个选项之外没有<option selected="0" /> <option selected="1" /> <option selected="false" /> <option selected="true" />

我无法使用selected,因为它不能与同一元素上的ngIf一起使用。

3 个答案:

答案 0 :(得分:6)

您可以使用ngModel来设置应该选择的元素。

<select [(ngModel)]="selectedItem" formControlName="template">
  <option *ngFor="let t of templates" [value]="t.id">{{t.title}}</option>
</select>

并在班级

var default = t.templates.find(v => v.is_default);
selectedItem = default && default.length && default[0].id;

答案 1 :(得分:1)

由于您使用的是模型驱动方法,为什么不在创建表单控件组期间在模型中设置值?

// select first (only?) default template
let defaultTemplate = this.templates.some((template) => template.is_default);
...
// create your form group and pass default template id as value for template select
this.yourForm = this.formBuilder.group({
    ...
    template: [defaultTemplate && defaultTemplate.id],
    ...
});

答案 2 :(得分:0)

如果你想做更复杂的事情,比如获取选项的文本,一种方法是将选项列表绑定到复杂的对象。

为您的对象创建一个界面: export interface Day { id: number; text: string }

然后为它提供一些值: this.days = [ { id: 1: text: 'Monday'}, { id: 2: text 'Teusday'} ]

然后在模板中使用它来创建选择列表。使用 ngValue 来绑定复杂对象非常重要。 <select [(ngModel)]="configDatas.days" name="days"> <option *ngFor="let day of days" [ngValue]="day">{{day.text}}</option> </select>

之后,显示它很简单: <span>You selected DayId: {{configDatas.days.id}}, Text: {{configDatas.days.text}}</span>

工作示例:http://plnkr.co/edit/iSr9dpwa10tHwKM45FAE?p=preview

相关问题