【发布时间】:2021-01-08 17:53:18
【问题描述】:
我有一个场景,比如添加/删除带有多个表单控件的表单组。
例如,
第一个下拉列表是国家/地区列表,第二个下拉列表是基于所选国家/地区的州列表,最后一个输入控件是 cmets。
问题是,当我加载页面时,默认情况下加载国家/地区下拉数据加载国家/地区 api,但根据所选国家/地区未正确加载各州。当我更改国家/地区时,所有其他国家/地区的下拉列表也发生了类似的变化。
例如,
这是我的尝试 HTML
<form [formGroup]='formName'>
<div formArrayName="controllerArray" class="ui-g ui-g-12 ui-g-nopad " >
<div class="ui-g ui-g-12 ui-g-nopad " *ngFor="let item of formName.controls.controllerArray.controls; let i=index" [formGroupName]="i">
<div class="ui-md-4">
<label class="mandatory"
>{{ labels["STATE_OF_INCORPORATION_FILE_NUMBER"] }}
<span class="colon"></span>
</label>
<select formControlName="select1" class="ui-inputtext" [(ngModel)]="item.controls.select1.value" (change)="changeAction($event,i)">
<option>--Select--</option>
<option *ngFor="let c of countryOptions" [value]="c.value">{{c.label}}</option>
</select>
</div>
<div class="ui-md-4">
<label class="lbl-hidden"> State </label>
<select formControlName="select2" class="ui-inputtext" [(ngModel)]="item.controls.select2.value">
<option>--Select--</option>
<option *ngFor="let b of businessStateOptions" [value]="b.value">{{b.label}}</option>
</select>
</div>
<div class="ui-md-3">
<label class="lbl-hidden"> comments </label>
<input
type="text"
pInputText
class="form-control"
formControlName="input"
/>
</div>
<div class="ui-md-1">
<label class="lbl-hidden"> State </label>
<br/>
<button (click)='removeInput(i)' style="min-width: auto;" pButton icon="fa fa-minus"></button>
</div>
</div>
</div>
</form>
<button class="add-remove-btn" pButton (click)='addInput()' icon="fa fa-plus"></button>`
Angular8 TS
import { Component, OnInit, ViewChild } from '@angular/core'
import { FormBuilder, Validators, FormArray } from '@angular/forms';
export class EntityEditComponent implements OnInit {
public countryOptions = [];
formName =this.fb.group({
controllerArray: this.fb.array([])
})
ngOnInit() {
this.countryOptions = [{"label":"United States","value":"US"},{"label":"Canada","value":"CA"}]
}
changeAction(e, index) {
if(index == 1 ) { // Here I'm trying to change the data if country is selected CA
let businessStateOptions = []
businessStateOptions= [{label:"Alberta",value:"CA"}]
const controlArray = <FormArray> this.formName.get('controllerArray');
controlArray.controls[index].get('select2').setValue( businessStateOptions);
}
}
addInput() {(this.formName.get('controllerArray') as FormArray).push(this.fb.group({select1:'', select2:'',input:''})) }
removeInput(index) { this.formName.controls.controllerArray["controls"].splice(index,1) }
}
预期结果是,
当我更改国家/地区时,需要将所选国家/地区的州加载到州下拉列表中,而不影响任何其他下拉列表。
【问题讨论】:
-
拜托哥们,它成功了吗?
-
不,它不工作。
标签: javascript angular typescript formarray