gpt4 book ai didi

Angular2 Reactive 表单 - 为带有下拉列表的表单字段设置默认值

转载 作者:太空狗 更新时间:2023-10-29 16:50:35 25 4
gpt4 key购买 nike

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

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

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

最佳答案

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

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

这也允许部分,所以你仍然可以做这样的事情:

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

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

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

关于Angular2 Reactive 表单 - 为带有下拉列表的表单字段设置默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39766029/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com