我尝试添加嵌套下拉列表。如果我们点击"添加城市",它将创建另一个下拉列表。我没有下拉就成功了。请看下面的
.. 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):物业&#39;推动&#39;类型&#39; AbstractControl&#39;。
上不存在E:/angular/nestedForm2/src/app/order-form/order-form.component.ts (23,42):财产&#39; removeAt&#39;类型&#39; AbstractControl&#39;。
上不存在
我尝试过不同的方法,但仍未找到任何解决方案。你能帮忙吗?
答案 0 :(得分:1)
要解决您遇到的错误,您需要将AbstractControl
投射到其子类FormArray
,其中push
和removeAt
已定义。
(this.form.get('cities') as FormArray).push(new FormControl())
(this.form.get('cities') as FormArray).removeAt(index)
您必须这样做,因为TypeScript无法确定form.get('cities')
的确切类型,因为您通过提供字符串来访问它。只有您作为开发人员才能根据表单中数据的结构知道form.get('cities')
将包含FormArray
。
答案 1 :(得分:0)
我找到了解决方案。
component.html:
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']); }
}
component.ts:
while 1
$res = ProcessExists("javaw.exe")
ConsoleWrite(ProcessExists("javaw.exe") & @CRLF)
if $res = 0 then
WinActivate("eclipse-workspace","")
sleep(500)
send("^{F11}")
EndIf
sleep(100)
WEnd