Angular2材质-无法将选定选项设置为md select
我正在尝试为客户端对象创建一个编辑表单, 首先,我从服务获取数据,然后初始化表单Angular2材质-无法将选定选项设置为md select,angular,material-design,angular-material,Angular,Material Design,Angular Material,我正在尝试为客户端对象创建一个编辑表单, 首先,我从服务获取数据,然后初始化表单 ngOnInit(){ this.clientService.getCountries().subscribe( (result:any) => { this.countries = result.countries; } ); this.subscription_route = this.route.params.subsc
ngOnInit(){
this.clientService.getCountries().subscribe(
(result:any) => {
this.countries = result.countries;
}
);
this.subscription_route = this.route.params.subscribe(
(params: any) =>{
if(params.hasOwnProperty('id')){
this.client_guid = params['id'];
this.subscription_service = this.clientService.getClient(this.client_guid).subscribe(
(result:any) => {
this.client = result.client;
this.initForm();
}
);
}
}
);
}
我的初始化表单如下所示:
private initForm(){
this.selectedOption = this.client.country_id;
this.clientForm = this.formBuilder.group({
name:[this.client.name,Validators.required],
email:[this.client.email],
vat_number:[this.client.vat_number],
payment_terms_id:[this.client.payment_terms_id],
address:[this.client.address],
city:[this.client.city],
postal:[this.client.postal],
country_id:[this.client.country_id],
accounting_key:[this.client.accounting_key],
payment_amount:[this.client.payment_amount]
});
}
然后在我的HTML模板中,我选择了这个md
<md-select placeholder="country" formControlName="country_id">
<md-option *ngFor="let country of countries" [value]="country.id">{{ country.name }}</md-option>
</md-select>
我无法设置从服务器获取的所选选项我到处搜索,没有找到任何答案,因此我尝试使用属性和属性。 我注意到,当我不使用*ngFor时,所选选项被选中,因此我认为问题在于[value]属性 这种方法对我很有效:
<md-select placeholder="country" [(ngModel)]="selectedOption" formControlName="country_id">
<md-option *ngFor="let country of countries" value="{{country.id}}">{{ country.name }}</md-option>
</md-select>
如果您使用的是复杂表单,您可以执行以下操作
<md-select placeholder="country" [formControl]="clientForm.controls['country_id']">
<md-option *ngFor="let country of countries" [value]="country.id">{{ country.name }}</md-option>
</md-select>
比如说
希望这有帮助
在您的回答中,将问题中的代码与[ngModel]解除链接,然后将所选选项的值与[ngModel]绑定。我想你可以查看这篇博文,了解更多关于Angular中绑定的信息:
clientForm.controls['country_id'].setValue(2);