使用下拉列表为表单字段设置默认值

使用下拉列表为表单字段设置默认值

本文介绍了Angular2 Reactive 表单 - 使用下拉列表为表单字段设置默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何为 angular 2 反应式表单中的所有表单字段设置默认值?

这是用于重现问题的 plnkr

下面的代码不会更新下拉值,因为它有一个与之关联的对象.

注意:这里我需要使用从后端 API 收到的响应为所有表单字段设置默认值.

组件.html

<div class="form-group"><label>国家:</label><select formControlName="国家"><option *ngFor="let country of masterCountries" [ngValue]="country">{{country.countryName}}</option></选择>

<div class="form-group"><label for="">名称</label><input type="text" class="form-control" formControlName="name"><small [hidden]="myForm.controls.name.valid || (myForm.controls.name.pristine && !submitted)" class="text-danger">姓名为必填项(最少 5 个字符).</小><!--<pre class="margin-20">{{ myForm.controls.name.errors |json }}</pre>-->

<button type="submit" class="btn btn-default">提交</button><div class="margin-20"><div>myForm 详细信息:-</div><pre>myForm 是否有效?:<br>{{myForm.valid |json}}</pre><pre>myForm 是否已提交?:<br>{{submitted |json}}</pre><pre>myForm 值:<br>{{myForm.value |json}}</pre>

组件.ts

导出类 AppComponent 实现 OnInit {公共 myForm:FormGroup;public masterCountries: any[] = [{"countryCode":"AF","countryName":"Afghanistan"},{"countryCode":"AL","countryName":"阿尔巴尼亚"},{"countryCode":"DZ","countryName":"阿尔及利亚"},{"countryCode":"AS","countryName":"美属萨摩亚"},{"countryCode":"AD","countryName":"Andorra"}];//从后端 api 接收的示例响应public CountryResponse = {country: {"countryCode":"AF","countryName":"阿富汗"}, name: 'test123'};构造函数(私有_fb:FormBuilder){}ngOnInit() {//捷径this.myForm = this._fb.group({国家: [''],名称:['', [

如果有其他方法可以设置整个表单,请告诉我.

解决方案

只需更改:

 (this.myForm).setValue(this.CountryResponse, {onlySelf: true});

进入这个:

const selectedCountry = this.masterCountries.find(country => country.countryCode === this.CountryResponse.country.countryCode)this.CountryResponse.country = selectedCountry;(<FormGroup>this.myForm).setValue(this.CountryResponse, {onlySelf: true});

如前所述,您需要传递对象的完全相同的引用

How can I set the default value for all forms fields in angular 2 reactive forms?

Here is the plnkr to reproduce the issue

Below code does not update dropdown values as it has an object associated with it.

Note: Here I need to set the default value for all form fields with the response received from Backend API.

Component.html

<form [formGroup]="myForm" novalidate (ngSubmit)="save(myForm.value, myForm.valid)">
    <div class="form-group">
        <label>Country:</label>
        <select formControlName="country">
          <option *ngFor="let country of masterCountries" [ngValue]="country">{{country.countryName}}</option>
        </select>
    </div>

    <div class="form-group">
      <label for="">Name</label>
      <input type="text" class="form-control" formControlName="name">
      <small [hidden]="myForm.controls.name.valid || (myForm.controls.name.pristine && !submitted)" class="text-danger">
            Name is required (minimum 5 characters).
          </small>
      <!--<pre class="margin-20">{{ myForm.controls.name.errors | json }}</pre>-->
    </div>
    <button type="submit" class="btn btn-default">Submit</button>
    <div class="margin-20">
      <div>myForm details:-</div>
      <pre>Is myForm valid?: <br>{{myForm.valid | json}}</pre>
      <pre>Is myForm submitted?: <br>{{submitted | json}}</pre>
      <pre>myForm value: <br>{{myForm.value | json}}</pre>
    </div>

Component.ts

export class AppComponent implements OnInit {
    public myForm: FormGroup;
    public masterCountries: any[] = [{"countryCode":"AF","countryName":"Afghanistan"},{"countryCode":"AL","countryName":"Albania"},{"countryCode":"DZ","countryName":"Algeria"},{"countryCode":"AS","countryName":"American Samoa"},{"countryCode":"AD","countryName":"Andorra"}];

    // Sample response received from backend api
    public CountryResponse = {country: {"countryCode":"AF","countryName":"Afghanistan"}, name: 'test123'};
    constructor(private _fb: FormBuilder) { }

    ngOnInit() {

        // the short way
        this.myForm = this._fb.group({
            country: [''],
            name: ['', [<any>Validators.required, <any>Validators.minLength(5)]],
        });


        (<FormGroup>this.myForm)
            .setValue(this.CountryResponse, {onlySelf: true});


    }


    save(model: User, isValid: boolean) {
        this.submitted = true;
        console.log(model, isValid);
    }
}

Let me know if there is any other way to set the whole form.

解决方案

Just change this:

 (<FormGroup>this.myForm)
            .setValue(this.CountryResponse, {onlySelf: true});

Into this:

const selectedCountry = this.masterCountries.find(country => country.countryCode === this.CountryResponse.country.countryCode)
this.CountryResponse.country = selectedCountry;
(<FormGroup>this.myForm)
            .setValue(this.CountryResponse, {onlySelf: true});

As said before you need to pass the exact same reference of the object

这篇关于Angular2 Reactive 表单 - 使用下拉列表为表单字段设置默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 02:14