I have a multi-select in Angular and want to set some initial values. See the following example: Stackblitz
Template
<form [formGroup]="filterFormGroup">
<mat-form-field color="accent">
<mat-label>{{ 'Users' }}</mat-label>
<mat-select formControlName="users" multiple>
<mat-option [value]="null">No User</mat-option>
<mat-option value="user1">User 1</mat-option>
<mat-option value="user2">User 2</mat-option>
<mat-option value="user3">User 3</mat-option>
</mat-select>
</mat-form-field>
</form>
Code
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl } from '@angular/forms';
@Component({
selector: 'app-component',
templateUrl: 'app.component.html',
})
export class AppComponent implements OnInit {
filterFormGroup = this.formBuilder.group({
users: [[]],
});
constructor(private formBuilder: FormBuilder) {}
ngOnInit() {
this.filterFormGroup.valueChanges.subscribe(x => console.log('changes: ' + JSON.stringify(x)));
const preselectedFilters = {
users: [null, 'user1']
};
this.filterFormGroup.setValue(preselectedFilters);
}
}
Please note that null is a valid option in my example and not some placeholder.
The values are correctly set but the "null-option" is not shown as selected... only the "user1"-option is shown.
Can anyone explain to me why it is not shown as selected and maybe even provide a solution to the problem?