Search code examples
angularformsangular4-formsangular-forms

Angular 2+ removeAt function not working in child component


I'm using for model driven for my form in angular4 .

I pass a formarray to child component by @input and when i use removeAt to it catch me an error :

removeAt is not a function

my parent 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() {

  }

}

my child 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.


Solution

  • That's because you're passing Array instead of FormArray.

    [_input]="spectra.controls"
    

    Try changing to

    [_input]="spectra"

    and child template should look like:

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

    Example