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

下面是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);
    }
}

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

推荐答案

只要改变这个:

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

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

Typescript相关问答推荐

通用默认值触发依赖通用约束变量的错误

之间是否有区别:例如useEffect()React.useEffect()

如何在另一个if条件中添加if条件

类型是工作.但它失go 了正确变体的亮点..为什么?或者如何增强?

为什么typescript要把这个空合并转换成三元?

`((PrevState:NULL)=>;NULL)|null`是什么意思?

typescribe警告,explate—deps,useEffect依赖项列表

如何根据另一个属性的布尔值来缩小函数属性的返回类型?

有没有办法解决相互影响的路由之间的合并?

打字脚本中泛型和直接类型重新映射的不同行为

使用2个泛型类型参数透明地处理函数中的联合类型

部分更新类型的类型相等

ANGLING v17 CLI默认设置为独立:延迟加载是否仍需要@NgModule进行路由?

使用KeyOf和Never的循环引用

如果数组使用Reaction-Hook-Form更改,则重新呈现表单

正确使用相交类型的打字集

类型';字符串|数字';不可分配给类型';未定义';.类型';字符串';不可分配给类型';未定义';

如何从一个泛型类型推断多个类型

为什么特定的字符串不符合包括该字符串的枚举?

带有过滤键的 Typescript 映射类型