[英]How can I set first option selected on ng-select angular 8?
I am generating multiple dropdowns from a nested array.我正在从嵌套数组生成多个下拉列表。 I wanted to first option selected for all dropdowns.
我想为所有下拉菜单选择第一个选项。 Here is my code on html
这是我在 html 上的代码
<ng-container *ngFor="let siz of product.attributes">
<ng-select autocomplete="attributes" formControlName="attributes" [ngClass]="{ 'is-invalid': submitted && val.get('attributes').errors }" class="mt-2" bindValue="{{ siz }}" bindLabel="{{ siz }}" [items]="siz.value" placeholder="Select {{ siz.name }}" (change)="sizeChange($event, siz.name)"></ng-select>
</ng-container>
Other everything working fine, I just need to first option selected by default.其他一切正常,我只需要默认选择第一个选项。
Get the value before everything in onInit在 onInit 中获取所有内容之前的值
selected = product.attributes.map(x => x.value.map(y => y)[0])[0];
Use method 1 while initializing your form在初始化表单时使用方法 1
Method 1:方法一:
//fb is formbuilder
this.form = fb.group({
attributes: [selected, Vaidators.required] // selected is the default value
});
Method 2: After form is initialized方法二:表单初始化后
this.form.controls['attributes'].setValue(selected);
.ts file .ts 文件
<ng-select formControlName="attributes">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.