Angular Material: mat-select not selecting default

后端 未结 17 1459
不思量自难忘°
不思量自难忘° 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:07

    As already mentioned in Angular 6 using ngModel in reactive forms is deprecated (and removed in Angular 7), so I modified the template and the component as following.

    The template:

    
        
            {{v.label}}
        
    
    

    The main parts of the component (onChanges and other details are omitted):

    interface SelectItem {
        label: string;
        value: any;
    }
    
    export class FilterComponent implements OnInit {
        filter = new FormControl();
    
        @Input
        selected: SelectItem[] = [];
    
        @Input()
        values: SelectItem[] = [];
    
        constructor() { }
    
        ngOnInit() {
            this.filter.setValue(this.selected);
        }
    
        compareFn(v1: SelectItem, v2: SelectItem): boolean {
            return compareFn(v1, v2);
        }
    }
    
    function compareFn(v1: SelectItem, v2: SelectItem): boolean {
        return v1 && v2 ? v1.value === v2.value : v1 === v2;
    }
    

    Note this.filter.setValue(this.selected) in ngOnInit above.

    It seems to work in Angular 6.

提交回复
热议问题