html - 如何动态地将 select 和 ng-select 重置为第一个选项
问题描述
更新 ::
https://stackblitz.com/edit/angular-ivy-tggo2e?file=src%2Fapp%2Fapp.component.ts
这个堆栈基本上是这篇文章的 TLDR。
更新 2::
好的,基本上在那场闪电战中,示例 2 有效。哈哈。在我的代码中,我在 API 调用之后在我的订阅中重置了 arr2,但在 API 调用修复它之前执行了它。现在我只需要弄清楚如何在初始加载时给它第一个选项(选择一些东西..)而不是一个空白框。
//////////////////
所以基本上我有一系列的选择下拉菜单。让我们称它们为 form1、form2、form3。
当我选择 form1 时,它将使用该选择调用 API 并动态地给我一个用于 form2 选项的数组。form3,4,5等相同。
现在到这里都没有问题。但是当我选择了 form1,2,3 然后再次选择 form1 时,我希望将表单 2 和 3 重置为我禁用的选项 1,但我似乎无法实现这一点。
Component.ts
dropdownForm() {
this.dropdownForm = new FormGroup({
form1: new FormControl(),
form2: new FormControl(),
form3: new FormControl(),
form4: new FormControl()
)}
callAPI(query) {
// API CALL
}
changeONE(e) {
// this.arr2 = [];
// reset this.dropdownForm.form2 back to the first option 1('Pick something..) to be 'selected' and 'disabled'
// this.callAPI(e)
}
changeTWO(e) {
// this.arr3 = []
// reset this.dropdownForm.form3
this.callAPI(e)
}
changeTHREE(e) {
// this.arr4 = []
// reset this.dropdownForm.form4 -- this one is ng-select so it is way different than the others.
// this.callAPI(e)
}
HTML
<form [formGroup]="dropdownForm">
<div>
<div>
<label for="form1">Form1</label>
<select id="form1"
(change)="changeONE($event)">
<option [value]="" selected disabled>Pick something..</option>
<option [value]="item" *ngFor="let item of arr">{{item}}</option>
</select>
</div>
<div>
<label for="form2">Form2</label>
<select id="form2"
(change)="changeTWO($event)">
<option [value]="" selected disabled>Pick something..</option>
<option [value]="item" *ngFor="let item of arr2">{{item}}</option>
</select>
</div>
<div>
<label for="form3">Form3</label>
<select id="form3"
(change)="changeTHREE($event)">
<option [value]="" selected disabled>Pick something..</option>
<option [value]="item" *ngFor="let item of arr3">{{item}}</option>
</select>
</div>
<div>
<label for="form4">Form4:</label>
<ng-select [multiple]="true" placeholder="Pick something" (change)="changeFOUR($event)" >
<ng-option *ngFor="let item of arr4">{{item}}</ng-option>
</ng-select>
</div>
我已经尝试在我的选择中添加 formControlname ,但是由于某种原因这使得选择行为很奇怪......也许是因为我的 'new FormControl('')' 是错误的?但这使我的 form1,2,3 只是在我的 optionsArr 中预先选择了一些随机的东西。
即使那样,如果我这样做 this.dropdownForm.controls.form1.reset() 或类似的东西,它也不会做任何事情。它只会重置值而不是重置下拉框(无论如何我什至都没有使用它..哈哈。我应该是,但我正在使用那个 changeONE() 和 $event 来获取值)
谢谢
编辑::
我刚试过
component.ts
this.dropdownForm.get('form2').reset()
HTML
<select id="form1"
(change)="changeONE($event)" formControlName='form1'>
基本上,当我选择了 form1 和 form2 并返回并使用 this.dropdownForm.get('form2').reset() 选择 form1 时,它不会重置 form2。相反,它将在该选择的第二个选项上选择新更新的 arr2 中的第一项(在我从该 API 调用中获取 arr2 之后),而不是转到该禁用的选项之一。