如何爲角度2反應形式中的所有表單字段設置默認值?Angular2反應形式 - 爲下拉式表單字段設置默認值
這裏是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);
}
}
讓我知道,如果有任何其他的方式來設置整個表單。
的可能的複製[角2 - 綁定對象下拉並選擇基於事件的值](http://stackoverflow.com/questions/39105905/angular-2-bind-object-to-dropdown-and-select-value-based-on- an事件) –
並且還有一個http://stackoverflow.com/questions/39745629/angular2-two-way-binding-to-select-option-not-u pdating –
它不是重複的。我需要使用從後端收到的示例響應更新所有表單域。更新我的問題,以反映相同的 –