Angular2 Reactive forms - 使用下拉菜单为表单域设置默认值?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (147)

我怎样才能设置角2反应形式的所有表单域的默认值?

这是plnkr重现问题

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

注意:在这里,我需要设置所有表单字段的默认值,并使用从后端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);
    }
}

让我知道是否有其他方式来设置整个表单。

提问于
用户回答回答于

只需改变这一点:

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

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

用户回答回答于

你的代码不起作用,因为尽管你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)]],
    });

扫码关注云+社区