Angular Material: mat-select not selecting default

后端 未结 17 1427
不思量自难忘°
不思量自难忘° 2020-11-28 23:18

I have a mat-select where the options are all objects defined in an array. I am trying to set the value to default to one of the options, however it is being left selected

17条回答
  •  野性不改
    2020-11-29 00:13

    I'm using Angular 5 and reactive forms with mat-select and couldn't get either of the above solutions to display the initial value.

    I had to add [compareWith] to deal with the different types being used within the mat-select component. Internally, it appears mat-select uses an array to hold the selected value. This is likely to allow the same code to work with multiple selections if that mode is turned on.

    Angular Select Control Doc

    Here's my solution:

    Form Builder to initialize the form control:

    this.formGroup = this.fb.group({
        country: new FormControl([ this.myRecord.country.id ] ),
        ...
    });
    

    Then implement the compareWith function on your component:

    compareIds(id1: any, id2: any): boolean {
        const a1 = determineId(id1);
        const a2 = determineId(id2);
        return a1 === a2;
    }
    

    Next create and export the determineId function (I had to create a standalone function so mat-select could use it):

    export function determineId(id: any): string {
        if (id.constructor.name === 'array' && id.length > 0) {
           return '' + id[0];
        }
        return '' + id;
    }
    

    Finally add the compareWith attribute to your mat-select:

    
    
    
        None
        
                            {{ country.name }}
        
    
    
    

提交回复
热议问题