[英]Select Box default value is not showing with [(ngModel)] Angular 2
[英]Material select box not showing binded value with ngModel - Angular2
我正在使用一个材质对话框组件,里面有一些材质输入框/选择框。
这是问题所在:
当对话框打开时,它从调用者组件接收一个在 dialogLocalModel 中复制的模型,该模型通过双向绑定绑定到 html。 除了最后一个,绑定效果很好。 这里的不同之处在于我们在保留在我们模型中的对象类型上使用 ngModel。
有人能解释一下为什么,当我进入对话框时,我可以看到第一个和第二个输入从绑定中填充得很好,但第三个仍然是空白的,即使它已经存储了一个信息(即一个对象)。
我不知道我是否已经清楚地解释了我的问题。 如果您有任何疑问,请咨询我。 为简单起见,我将在以下代码中留下一些注释。
这是代码的核心部分:
调用对话框的组件
[...]
public editAsset(model){ //this method open the dialog
let dialogRef = this.dialog.open(AssetsDialogComponent, <MatDialogConfig>{
width: '80%',
data: {
mode : "edit",
/*
passing the data model (with this shape)
model = {index:string ,denomination: string,category :object }
*/
assetModel : model
}
});
//other part that work after closing of the dialog
}
调用的对话框组件
export class AssetsDialogComponent implements OnInit {
public localAssetModel = {
id : null,
index: '',
denomination: '',
category: <CatAssets> null,
};
public catAssetList: CatAssets[];
constructor(private assetsService: AssetsService,
private catService: CategorieService,
public dialogRef: MatDialogRef<AssetsDialogComponent>,
@Inject(MAT_DIALOG_DATA) public data: any) {
}
ngOnInit() {
this
.catService
.getCategories(CategoryTypes.Assets)
.then(res => {
this.catAssetList = res;
})
.catch(error => AppHTTPService.handleErrorPromise(error));
this.initLocalModel(this.data.mode);
}
private initLocalModel(mode) {
if(mode == "edit"){
this.localAssetModel.id = this.data.assetModel.id;
this.localAssetModel.index = this.data.assetModel.index;
this.localAssetModel.denomination = this.data.assetModel.denomination;
this.localAssetModel.category = this.data.assetModel.category;
}
绑定到 TS 逻辑的对话框的 HTML
<div class="col-lg-4">
<fieldset class="form-group">
<mat-form-field>
<mat-select
placeholder="Categoria Asset"
[(ngModel)]="localAssetModel.category"
name="category"
required
>
<mat-option *ngFor="let category of catAssetList" [value]="category" >
{{category.categoryId}}
</mat-option>
</mat-select>
</mat-form-field>
</fieldset>
</div>
因为我们正在处理您的选择对象,角度不知道如何搭配localAssetModel.category
在阵列catAssetList
,因为他们没有提及对方。
您可以选择使用.find()
创建引用:
this.localAssetModel.category = this.catAssetList.find(x =>
x.categoryId === this.data.assetModel.category.categoryId);
但是这意味着你需要调用initLocalModel
回调then
,让我们相信, catAssetList
有价值观,即做:
.then(res => {
this.catAssetList = res;
this.initLocalModel(this.data.mode);
})
.catch(error => AppHTTPService.handleErrorPromise(error));
另一种选择是使用compareWith
:
<mat-select [(ngModel)]="localAssetModel.category" [compareWith]="compareWithFn">
在 TS 中:
compareFn(item1,item2){
return item1.categoryId == item2.categoryId;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.