问题
I'm trying to edit some member's firebase data with a mat-select component composed of different types.
I'm not sure with my structure of nodes but I did this :
member:
member1:
name:
types:
typekey1 : Title1
typekey3 : Title3
...
types:
typekey1:
key: typekey1
title: Title1
typekey2:
key: typekey2
title: Title2
typekey3:
key: typekey3
title: Title3
...
So I can't make the following function
compareFn(t1: Type, t2: Type): boolean {
return t1 && t2 ? t1.key === t2.key : t1 === t2;
}
to work with the template
<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>
I can't seem to find the way to connect the two kind of type in the compareFn function and have selected the option when the component is launched
回答1:
For an object of the following structure:
listOfObjs = [{ name: 'john', id: '1'}, { name: 'jimmy', id: '2'},...]
Define markup like this:
<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>
And define comparison function like this:
compareObjects(o1: any, o2: any) {
if(o1.name == o2.name && o1.id == o2.id )
return true;
else return false
}
回答2:
<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;
}
来源:https://stackoverflow.com/questions/47477167/use-comparewith-function-from-angular-material-mat-select-component-with-linked