Reputation: 11864
I have this TypeScript:
public sendAlertDays: Array<any> = [
{ value: [0, 1, 2, 3, 4, 5, 6], text: "all days" },
{ value: [0, 1, 2, 3, 4], text: "monday-friday" },
{ value: [5, 6], text: "saturday-sunday" },
{ value: [0], text: "monday" },
{ value: [1], text: "tuesday" },
{ value: [2], text: "wednesday" },
{ value: [3], text: "thursday" },
{ value: [4], text: "friday" },
{ value: [5], text: "saturday" },
{ value: [6], text: "sunday" }
];
sendAlertDay: number[] = [0];
My Angular template do not pre-select 'monday' yet I have initialized well sendAlertDay: number[] = [0]
<mat-select [(value)]="sendAlertDay" class="mat-primary">
<mat-option *ngFor="let day of sendAlertDays" [value]="day.value">
{{day.text}}
</mat-option>
</mat-select>
Upvotes: 2
Views: 1531
Reputation: 6529
You will need to use the compareWith
property of the mat-select
.
@Input() compareWith: (o1: any, o2: any) => boolean
Function to compare the option values with the selected values. The first argument is a value from an option. The second is a value from the selection. A boolean should be returned.
Your component:
public sendAlertDays: Array<any> = [
{ value: [0, 1, 2, 3, 4, 5, 6], text: "all days" },
{ value: [0, 1, 2, 3, 4], text: "monday-friday" },
{ value: [5, 6], text: "saturday-sunday" },
{ value: [0], text: "monday" },
{ value: [1], text: "tuesday" },
{ value: [2], text: "wednesday" },
{ value: [3], text: "thursday" },
{ value: [4], text: "friday" },
{ value: [5], text: "saturday" },
{ value: [6], text: "sunday" }
];
sendAlertDay: number[] = [0];
compareFN(optionValue: number[], selectionValue: number[]) {
// compare two arrays
return (
optionValue.length === selectionValue.length &&
optionValue.every((value, index) => value === selectionValue[index])
);
}
Your template:
<mat-select [(value)]="sendAlertDay" [compareWith]="compareFN" class="mat-primary">
<mat-option *ngFor="let day of sendAlertDays" [value]="day.value">
{{day.text}}
</mat-option>
</mat-select>
Demo on stackblitz
Upvotes: 2
Reputation: 1334
You can not set the selected value to be an array.
in order for this to work you need to set the value to be string
instead of number[]
this for example would work :
public sendAlertDays: Array<any> = [
{ value: 'all', text: 'all days' },
{ value: 'monday-to-friday', text: 'monday-friday' },
{ value: 'saturday-sunday', text: 'saturday-sunday' },
{ value: 'monday', text: 'monday' },
{ value: 'tuesday', text: 'tuesday' },
{ value: 'wednesday', text: 'wednesday' },
{ value: 'thursday', text: 'thursday' },
{ value: 'friday', text: 'friday' },
{ value: 'saturday', text: 'saturday' },
{ value: 'sunday', text: 'sunday' }];
sendAlertDay: string = 'monday';
here's a stackblitz: https://stackblitz.com/edit/angular-2wzrmk-se36mv
an alternative would be to set the value to number
, this would work as well
Upvotes: 0