我在angular4中使用模型驱动我的表单。
我通过formarray
将@input
传递给子组件,当我使用removeAt时,它会发现错误:
removeAt不是函数
我的父组件
<form class="ui form" [formGroup]="gform" (ngSubmit)="doSave(gform.value)">
<app-tag-input [_input]="spectra.controls" ></app-tag-input>
</form>
parentcoponent.ts
gform: FormGroup;
get spectra(): FormArray { return this.gform.get('spectra') as
FormArray; }
ngOnInit() {
this.spectra.insert(0, this.initSpectrum(' very good'));
this.spectra.insert(1, this.initSpectrum('good'));
this.spectra.insert(2, this.initSpectrum('normal'));
this.spectra.insert(3, this.initSpectrum('need to more try'));}
childcoponent.ts:
export class TagInputComponent implements OnInit {
@Input() _input :FormArray;
tagEntry:string;
constructor(private formBuilder:FormBuilder) {
formBuilder.array
}
addToInput() {
const formGroup=this.formBuilder.control(
this.tagEntry
);
const order = this._input.length + 1;
this._input.push(formGroup)
this.tagEntry='';
}
removeSpectrum=(i: number)=> {
const control = <FormArray>this._input;
control.removeAt(i);
}
ngOnInit() {
}
}
我的孩子component.html
<div class="tagsinput">
<span *ngFor="let item of _input let i=index" class="ui teal label">
{{item.value}}
<i class="close icon" (click)="removeSpectrum(i)"></i>
</span>
<input type="text" [(ngModel)]="tagEntry" [ngModelOptions]="{standalone: true}" (keyup.enter)="addToInput()"/>
</div>
当我在两个组件中控制formarray时,父组件spectra
中存在一个控件对象,该控件对象不在子组件的_input中。
答案 0 :(得分:3)
那是因为你传递了Array
而不是FormArray
。
[_input]="spectra.controls"
尝试更改为
[_input]="spectra"
和子模板应如下所示:
*ngFor="let item of _input.controls
^^^^^^^^^^
add this
<强> Example 强>