In angular html template I have multiselect (plain bootstrap multiselect) like in html here:
<form [formGroup]="globalScriptForm">
...
<div class="form-group">
<label for="events">Events</label>
<select multiple class="form-select"
type="text"
id="events"
formControlName="events">
<option value=0>a</option>
<option value=1>b</option>
<option value=2>c</option>
</select>
</div>
...
</form>
and here is code from controller:
export class GlobalScriptEditComponent implements OnInit {
globalScriptForm!: FormGroup;
ngOnInit(): void {
let events: number[] = [0,1];
this.globalScriptForm = new FormGroup({
'events': new FormControl(events),
});
}
}
Question would be how can I make multi-select options in html template selected based on values in events array from controller, eg [0,1]?
ie get this result in html (notice word selected next to options 0 and 1, as these are values in array)
<div class="form-group">
<label for="events">Events</label>
<select multiple class="form-select"
type="text"
id="events"
formControlName="events">
<option value=0 selected>a</option>
<option value=1 selected>b</option>
<option value=2>c</option>
</select>
</div>
Hope it is somehow clearer now. Thanks!
list of options should be added to ts file:
optionsList = ['a', 'b', 'c'];
and it should be used in html file like this:
<form [formGroup]="globalScriptForm">
...
<div class="form-group">
<label for="events">Events</label>
<select multiple class="form-select"
type="text"
id="events"
formControlName="events">
<option *ngFor="let option of optionsList; let i = index" [value]="i">{{option}}</option>
</select>
</div>
...
</form>
instead of hardcoding it (as presented above).
Everything else should not be changed. Turned out to be simple solution after all 🙂
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.