Angular2 Reactive forms - 使用下拉菜单设置表单字段的默认值

新手上路,请多包涵

如何为 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);
    }
}

让我知道是否有其他方法可以设置整个表单。

原文由 Narendra CM 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 539
2 个回答

只需更改此:

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

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

原文由 Fabio Antunes 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

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

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

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

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

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

原文由 DeBorges 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进