【问题标题】:Angular 2+ removeAt function not working in child componentAngular 2+ removeAt 函数在子组件中不起作用
【发布时间】:2018-06-24 03:28:55
【问题描述】:

我在 angular4 中为我的表单使用模型驱动。

我通过@inputformarray 传递给子组件,当我使用removeAt 时它发现我一个错误:

removeAt 不是函数

我的父组件.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() {

  }

}

我的子组件.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>

当我在 tow 组件中控制台 formarray 时,父组件 spectra 中存在一个控件对象,而子组件中的 _input 中不存在。

【问题讨论】:

    标签: angular forms angular4-forms angular-forms


    【解决方案1】:

    那是因为您传递的是 Array 而不是 FormArray

    [_input]="spectra.controls"
    

    试试改成

    [_input]="spectra"

    子模板应如下所示:

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

    Example

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-16
      • 2012-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-27
      • 2019-03-29
      相关资源
      最近更新 更多