我试图添加嵌套下拉。如果我们点击“添加城市”,它会创建另一个下拉菜单。我没有下拉式成功。请参见下文角4嵌套下拉
..component.html
<form [formGroup]="form" (ngSubmit)="onSubmit()">
<select formControlName="cities">
<option *ngFor="let city of myCities; let i=index" [value]='itemname' >
{{ city }}
</option>
</select>
<br>
<button>Submit</button>
<button (click)="addCity()">Add City</button>
<button (click)="remove(i)">Remove</button>
</form>
component.ts
form = new FormGroup({
cities: new FormControl([null]),
});
myCities = ['Dhaka','Dubai','Munich'];
get cities(): FormArray { return this.form.get('cities') as FormArray; }
addCity() { this.form.get('cities').push(new FormControl())}
remove(index){ this.form.get('cities').removeAt(index) }
显示错误波纹管:
E:/angular/nestedForm2/src/app/order-form/order-form.component.ts (21,39): Property 'push' does not exist on type 'AbstractControl'.
E:/angular/nestedForm2/src/app/order-form/order-form.component.ts (23,42): Property 'removeAt' does not exist on type 'AbstractControl'.
我已经TR以不同的方式,但仍然没有找到任何解决方案。能否请你帮忙?
谢谢拉扎尔。你能告诉我如何施展? – Tanvir
我在回答中提供了一段代码片段。正如我在那里展示的那样,你使用'as'来投射。 –
我做了这个addCity(){(this.form.get('cities')as FormArray).push(new FormControl())}&remove(index){(this.form.get('cities')as FormArray).removeAt(index)}。但仍然发现错误“ERROR TypeError:this.form.get(...)。push不是函数” – Tanvir