角4嵌套下拉
问题描述:
我试图添加嵌套下拉。如果我们点击“添加城市”,它会创建另一个下拉菜单。我没有下拉式成功。请参见下文角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以不同的方式,但仍然没有找到任何解决方案。能否请你帮忙?
答
我找到了解决方案。
component.html:
<form [formGroup]="form" (ngSubmit)="onSubmit()">
<div formArrayName="cities">
<div *ngFor="let city of cities.controls; let i=index">
<select [formControlName]="i">
<option *ngFor="let itemname of myCities" [value]='itemname' >
{{ itemname }}
</option>
</select>
</div>
</div>
<br>
<button>Submit</button>
</form>
<br>
<button (click)="addCity()">Add City</button>
<button (click)="remove(i)">Remove City</button>
component.ts:
import { AbstractControl, FormArray, FormControl, FormGroup } from '@angular/forms';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-order-form',
templateUrl: './order-form.component.html',
styleUrls: ['./order-form.component.css']
})
export class OrderFormComponent implements OnInit {
form = new FormGroup({
cities: new FormArray([
new FormControl([null]),
]),
});
myCities = ['Dhaka','Dubai','Munich'];
get cities(): FormArray { return this.form.get('cities') as FormArray; }
addCity() { this.cities.push(new FormControl()); }
remove(index) { (this.form.get('cities') as FormArray).removeAt(index) }
constructor() { }
ngOnInit() {
}
onSubmit() {
console.log(this.cities.value); // ['SF', 'NY']
console.log(this.form.value); // { cities: ['SF', 'NY'] }
}
setPreset() { this.cities.patchValue(['LA', 'MTV']); }
}
答
要解决您的错误,您需要将AbstractControl
转换为其子类FormArray
,其中push
和removeAt
已定义。
(this.form.get('cities') as FormArray).push(new FormControl())
(this.form.get('cities') as FormArray).removeAt(index)
你必须这样做,因为打字稿不能确定的form.get('cities')
确切类型,因为你通过提供字符串访问它。只有您作为开发人员知道,根据您表单中的数据结构,form.get('cities')
将包含FormArray
。
谢谢拉扎尔。你能告诉我如何施展? – 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