简体   繁体   English

如何设置Angular 2反应形式的下拉菜单(选择选项)的默认值

[英]How can I set default value of dropdown (select-option) input in Angular 2 reactive form

I have a dropdown list of objects. 我有一个对象下拉列表。 It's a person object that has a properties of id , firstName and lastName . 这是一个具有idfirstNamelastName属性的人员对象。

<select formControlName="person">
    <option *ngFor='let person of persons" [ngValue]="person">{{person.firstName+' '+person.lastName}}</option>
</select>

Let' say I have an object person which I want to check if this person object I have is in the dropdownlist. 假设我有一个对象人,我想检查我拥有的这个人对象是否在下拉列表中。 If exist I want that object person to be the selected option /default value of the dropdown list. 如果存在,我希望该对象对象成为下拉列表的选定选项/默认值。

You can make use of the formControl and set the default value with that. 您可以使用formControl并设置默认值。 Depending on if you have the value on initialization of the component, you can set the value when you build the form, otherwise use patchValue when you have received the value. 根据在组件初始化时是否具有该值,可以在构建表单时设置该值,否则在收到该值时使用patchValue So when you build the form (if you have the data) 因此,当您构建表单时(如果有数据)

ngOnInit() {
  this.myForm = this._fb.group({
    person: [this.persons[1]]
  }); 
}

Demo 演示

PS, usually we do not use ngValue here, which binds the whole object, but of course this also works if you want/need to do it :) PS,通常我们在这里不使用ngValue ,它绑定了整个对象,但是如果您希望/需要这样做,当然也可以使用:)

Approach without using ngModel..You can also select default value of dropdown using index (i) of each iteration inside *ngFor . 不使用ngModel的方法。您还可以使用* ngFor中每个迭代的索引(i)选择下拉列表的默认值。 You can use 'selected' property on option element and then set the value of index (i) equivalent to which option you want to make default. 您可以在选项元素上使用'selected'属性,然后将索引(i)的值设置为与要设为默认选项的选项等效。 Here I have made 2nd option to be by-Default selected. 在这里,我默认选择了第二个选项。 Index is the index of each option in an array. 索引是数组中每个选项的索引。 Below is the code modified a bit for the same: 下面是将代码修改为相同的代码:

@Component({ selector: 'my-app', template: ` {{option.name}} @Component({选择器:“ my-app”,模板:`{{option.name}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM