I understand that to default a mat-select to certain values, you need to create an array and set the FormControl's value to that array. However, I'm having trouble getting this to work for more complicated objects, like the following:
public formGroupCarForm: FormGroup;
public formBuilder: FormBuilder;
allCars: Car[] [
{ id: 1, name: "Honda Accord", year: "1995" },
{ id: 2, name: "Toyota Camry", year: "1999" },
{ id: 3, name: "Audi A6", year: "2011" }
];
constructor() {
this.setDropdowns();
}
public setDropdowns() {
allCarsFilter: Car[] = this.allCars;
allCarsFilter = [...allCarsFilter, { id: 0, name: "All", year: "0000" }];
this.formGroupCarForm = this.formBuilder.group({
carFilter: new FormControl(allCarsFilter); // This doesn't work
});
}
I also have the following HTML, which has a hard-coded "All" option:
<form [formGroup]="formGroupCarForm">
<mat-form-field class="filter-field" appearance="outline">
<mat-select multiple floatLabel="always" formControlName="carFilter">
<mat-option (click)="toggleAllSelection()" #toggleCar value="">All</mat-option> <!-- I also don't know what to put for the value here??? -->
<mat-option *ngFor="let car of allCars" [value]="car.id">{{ car.name + ' - ' + car.year }}</mat-option>
</mat-select>
</mat-form-field>
</form>
I'd like to select all of the values, including the "All" option by default. I was really hoping that the carFilter: new FormControl(allCars);
line would at least select the ngFor mat-options, but they're not being selected. I have it working for other dropdowns though, but those dropdowns are based off of more primitive data types like numbers and strings. How would I go about doing this for an object like this?