Topic: ng-select How to programmatically set a value ?
vizmedia pro asked 7 years ago
this.optionsSelect = [ { value: '1', label: 'Option 1' }, { value: '2', label: 'Option 2', SELECTED: true }, { value: '3', label: 'Option 3' }, ]; or this.optionsSelect[3].selected = true;How to set the value programmatically ?
Damian Gemza staff answered 6 years ago
<div class="row"> <div *ngFor="let select of selecty; let index" class="col-md-4 mx-auto my-5"> <mdb-select #selects id="{{index}}" [options]="optionsSelect" placeholder="Choose your option"></mdb-select> <label>Example label</label> </div> </div>
optionsSelect: Array<any>; selecty: Array<any> = [1, 2, 3]; @ViewChildren('selects') selects: QueryList<any>; ngOnInit() { this.optionsSelect= [ { value: '1', label: 'Option 1' }, { value: '2', label: 'Option 2' }, { value: '3', label: 'Option 3' }, ]; } ngAfterViewInit() { this.selects.forEach((element) => { setTimeout(() => { if (element.el.nativeElement.attributes.id.value == 1) { element.select(this.optionsSelect[0].value); } else if (element.el.nativeElement.attributes.id.value == 2) { element.select(this.optionsSelect[1].value); } else if (element.el.nativeElement.attributes.id.value == 3) { element.select(this.optionsSelect[2].value); } }, 0); }); }
Rafał Rogulski free answered 7 years ago
Hi,
First, you need to create a reference to your select:
<ng-select #myselect [options]="optionsSelect" placeholder="Choose your option" #myselect></ng-select>
now you can access to .select() method from template file:
<button (click)="myselect.select('2')">Select 2</button>
or you can get a reference in your component typescript with ViewChild:
import { Component, ViewChild } from '@angular/core';
@Component({selector:'app-root',
selector:'app-root',
templateUrl:'app.component.html'
})
export class AppComponent {
@ViewChild('myselect') myselect;
optionsSelect:Array<any>;
constructor() {
this.optionsSelect= [
{ value: '1', label: 'Option 1' },
{ value: '2', label: 'Option 2' },
{ value: '3', label: 'Option 3' },
];
}
setNew() {
this.myselect.select(this.optionsSelect[0].value);
}
}
Regards
Michael Nino free commented 6 years ago
Using your example above, how do I make #myselect dynamic? I use *ngFor to create a variable number of ng-select. It seems using # is the only way to get a instance of ng-select within the component's typescript.FREE CONSULTATION
Hire our experts to build a dedicated project. We'll analyze your business requirements, for free.
Resolved
- ForumUser: Pro
- Premium support: No
- Technology: MDB Angular
- MDB Version: -
- Device: -
- Browser: -
- OS: -
- Provided sample code: No
- Provided link: No