【问题标题】:Angular2 Reactive forms - Set default value for form fields with dropdownAngular2 Reactive forms - 使用下拉菜单设置表单字段的默认值
【发布时间】:2017-02-07 12:39:16
【问题描述】:

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

这里是plnkr 重现问题

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

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

组件.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>

组件.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);
    }
}

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

【问题讨论】:

标签: angular typescript angular2-forms


【解决方案1】:

我知道这是一个老问题,但如果有人寻找它,现在有一种更好的方法来设置整个表单的值,PatchValue

this.myForm.patchValue({
   country: this.CountryResponse,
   name: 'Any Name'
});

这也允许部分,因此您仍然可以执行以下操作:

this.myForm.patchValue({ country: this.CountryResponse });

或者您可以将值设置为单个控件:

this.myForm.get('country').setValue(this.CountryResponse);

【讨论】:

    【解决方案2】:

    当你声明表单控件或初始化时,传递默认值作为参数

      MyFormControl: FormControl = new FormControl('Default value');
    

    【讨论】:

    • 最干净的方法
    • 我认为这是一种更简洁的实现方式。它对我有用,谢谢
    【解决方案3】:

    只要改变这个:

     (<FormGroup>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});
    

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

    【讨论】:

    • patchValue 更合适
    【解决方案4】:

    您的代码不起作用,因为尽管您的this.selectedCountry 似乎与this.masterCountries 的元素之一具有相同的字段值,但它们不是同一个对象。这使得select.value === option.value 比较总是返回false

    让它工作起来很简单,只需将您的setValue 函数更改为如下:

    (<FormControl>this.form.controls['country'])
                .setValue(this.masterCountries[0], { onlySelf: true });
    

    或者你可以在创建FormGroup时设置它:

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

    【讨论】:

    • 感谢您的回答。是的,如果我使用 masterCountries 设置值,它会起作用。但是我需要使用从后端收到的响应来设置整个表单。用这个场景更新了我的 plnkr。 plnkr.co/edit/GKguMzZbr0kzrraPP73f?p=preview
    猜你喜欢
    • 1970-01-01
    • 2021-03-19
    • 1970-01-01
    • 2011-08-17
    • 2018-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多