Use compareWith function from Angular Material mat-select component with linked firebase value

…衆ロ難τιáo~ 提交于 2019-12-22 04:45:41

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!