我试图用由不同类型组成的垫子选择组件编辑某些成员的火库数据。
我不确定我的节点结构,但我这样做了:
member:
member1:
name:
types:
typekey1 : Title1
typekey3 : Title3
...
types:
typekey1:
key: typekey1
title: Title1
typekey2:
key: typekey2
title: Title2
typekey3:
key: typekey3
title: Title3
...
所以我无法制作以下功能
compareFn(t1: Type, t2: Type): boolean {
return t1 && t2 ? t1.key === t2.key : t1 === t2;
}
使用模板
<mat-form-field>
<mat-select [compareWith]="compareFn" [(ngModel)]="member.types" multiple>
<mat-option
*ngFor="let type of types | async"
[value]="type">
{{type.title}}
</mat-option>
我似乎找不到将两种类型连接在compareFn函数中的方法,并在启动组件时选择了该选项
对于以下结构的对象:
listOfObjs = [{ name: 'john', id: '1'}, { name: 'jimmy', id: '2'},...]
这样定义标记:
<mat-form-field>
<mat-select
[compareWith]="compareObjects"
[(ngModel)]="obj">
<mat-option *ngFor="let obj of listOfObjs" [value]="obj">
{{ obj.name }}
</mat-option>
</mat-select>
</mat-form-field>
和这样的比较函数这样:
compareObjects(o1: any, o2: any) {
if(o1.name == o2.name && o1.id == o2.id )
return true;
else return false
}
这是一个示例:
<mat-select [compareWith]="compareFn" [(ngModel)]="defaultItem">
<mat-option *ngFor="let country of countries" [value]="item">
{{country.name}}
</mat-option>
</mat-select>
compareFn(c1: Country, c2: Country): boolean {
return c1 && c2 ? c1.id === c2.id : c1 === c2;
}
参考:我在这里回答,https://stackoverflow.com/a/63539749/10373693
<mat-select [compareWith]="compareFn" [(ngModel)]="defaultItem">
<mat-option *ngFor="let item of items" [value]="item">
{{item.title}}
</mat-option>
</mat-select>
items: Item[];
defaultItem: Item = {
slug: 'test',
title: 'Test'
};
compareFn(o1: any, o2: any) {
return o1.slug === o2.slug;
}