I've created a multiple select dropdown but in that list I would like to make auto select.
for example:
String[] names = ["ant", "bat", "cat", "dog"];
String[] autoSelectName = ["bat", "dog"];
So what I exactly want that I would like to bat and dog should be selected when I'll open the dropdown.
.html
<mat-form-field id="name-dropdown">
<mat-select formControlName="names" multiple>
<mat-option *ngFor="let name of names" [value]="name">
{{name}}
</mat-option>
</mat-select>
</mat-form-field>
Thanks in advance.
CodePudding user response:
You only need "feed" with an array the formControl, e.g.
using pathValue:
this.form.pathValue({names:this.autoSelectName})
using setValue to the control:
this.form.get('names').setValue(this.autoselectName)
When you create the form using the contructors:
this.form=new FormGroup({
names:new FormControl(this.autoSelectName,Validators.required)
})
Using formBuilder
this.form=this.fb.group({
names:[this.autoSelectName,Validators.required]
})
Even you neen't an auxiliar variable
this.form=this.fb.group({
names:[["bat", "dog"],Validators.required]
})