我在angular4中为我的表单使用模型驱动。
我通过formarray将一个@input传递给子组件,当我使用removeAt时,会发现一个错误:
removeAt不是一个函数
我的父母component.html
<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>当我在两个组件中控制台格式化数组时,父组件spectra中存在一个控制对象,而子组件中的_input中不存在一个控制对象。
发布于 2018-01-15 13:59:49
这是因为您传递的是Array而不是FormArray。
[_input]="spectra.controls"试着换到
[_input]="spectra"
子模板应该如下所示:
*ngFor="let item of _input.controls
^^^^^^^^^^
add thishttps://stackoverflow.com/questions/48264025
复制相似问题