I have my code in HTML like this.
<div class="col-md-10">
<ng-select [items]="tests" (data)="updateSelected($event, 'test')">
</ng-select>
</div>
My typescript code is as follows
@Input() tests: Option[] = []; I have tests coming as input from previous component
@ViewChildren(SelectComponent)
private selectComponents: QueryList<SelectComponent>;
ngAfterViewInit() {
this.selectComponents;
}
How do I set some value as default value here in selectComponents or is there any other way to set some value as default value using ng-select.
Use ngModel binding as below.
<ng-select options="users" [(ngModel)]="selectedValue">
</select>
ngOnInit() {
this.selectedValue = ["1"]
}
Array item value is option id. https://basvandenberg.github.io/ng-select may be helpful for you.
For Reactive forms, you can bind the value while creating `FormGroup`.
In TS:
import { FormBuilder, Validators, FormGroup} from '@angular/forms';
accountForm: FormGroup; // declaring form group
constructor(private fb: FormBuilder) {}
ngOnInit(): void {
this.createForm();
}
createForm(): void {
this.accountForm = this.fb.group({
trial: ['Yes', [Validators.required]] // Its default value
});
}
In case, if the value is dynamic (eg. from API call), you can set it with
this.accountForm.patchValue({trial: 'abcd'});
In HTML:
<form class="form"
[formGroup]="accountForm"
(ngSubmit)="onSubmit(accountForm)"
autocomplete="off"
novalidate>
<div class="form-row">
<div class="col-sm-4" >
<div class="form-group">
<label>Trial</label>
<ng-select
[items]="booleanDropdown"
[multiple]="false"
[selectableGroup]="true"
[closeOnSelect]="true"
[clearable]="false"
formControlName="trial">
</ng-select>
</div>
</div>
</div>
You have to either define a component type object for the variable or or you can get the first element of the list and set it as a defualt variable.
@ViewChildren(SelectComponent) private selectComponents: QueryList<SelectComponent>;
defualtComponent: any; ngAfterViewInit() { this.defaultComponent = this.selectComponents.get(0); }
This will select the first element if that is what you want as ypur default element.