简体   繁体   English

Angular 2+ removeAt函数在子组件中不起作用

[英]Angular 2+ removeAt function not working in child component

I'm using for model driven for my form in angular4 . 我正在为angular4中的表单驱动模型。

I pass a formarray to child component by @input and when i use removeAt to it catch me an error : 我通过@inputformarray传递给子组件,当我使用removeAt时,它捕获了一个错误:

removeAt is not a function removeAt不是函数

my parent component.html 我的父母component.html

<form class="ui form" [formGroup]="gform" (ngSubmit)="doSave(gform.value)">
<app-tag-input [_input]="spectra.controls"  ></app-tag-input>
</form>

parentcoponent.ts 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: 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() {

  }

}

my child component.html 我的孩子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>

when i console formarray in tow component an control object exist in parent component spectra that not in _input in child component. 当我在拖曳组件中控制formarray时,控制组件存在于父组件spectra ,而不存在于子组件的_input中。

That's because you're passing Array instead of FormArray . 那是因为您要传递Array而不是FormArray

[_input]="spectra.controls"

Try changing to 尝试更改为

[_input]="spectra"

and child template should look like: 和子模板应如下所示:

*ngFor="let item of _input.controls
                         ^^^^^^^^^^
                       add this

Example

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM