Testing FormArray

故事扮演 提交于 2019-12-06 04:19:27

问题


I have a PhoneNumbersFormComponent whose template looks like :

<div [formGroup]="form">
    <div formArrayName="numbers">
      <input formControlName="countryPrefix">
      <input formControlName="number">
    </div>
</div>

I want to pass the default test created by angular-cli's ng g component xxx

The first error I got was:

Cannot find control with name 'countryPrefix'

Which I solved with:

  beforeEach(() => {
    fixture = TestBed.createComponent(PhoneNumbersFormComponent);
    component = fixture.componentInstance;
    component.phoneNumbers = [];
    component.form = new FormGroup({
      countryPrefix: new FormControl(),
      number: new FormControl()
    });
    fixture.detectChanges();
  });

Now the last remaining error is:

Cannot find control with name 'numbers'

And I have no idea how to test formArrayName="numbers"


回答1:


Try something like this:

let array: FormGroup[] = [];
array.push(new FormGroup({
      countryPrefix: new FormControl(),
      number: new FormControl()
}));
let formArray = new FormArray(array);
component.form = new FormGroup({
       numbers: formArray // or array not totally sure
})



回答2:


Alternatively you can build a FormArray in your component and provide a getter for the form array.

ngOnInit() { this.formArrayOfPhoneNumbers = this.phoneNumbers.map((phone) => 
    { return new FormGroup({ countryPrefix: [phone.countryPrefix], number: [phone.number] })
}

get numbers: FormArray { return this.formArrayOfPhoneNumbers as FormArray }

I'm not exact on the syntax most likely, but the point is that the formArrayName directive will call the getter and you can ensure that a FormArray object is being returned.



来源:https://stackoverflow.com/questions/46723685/testing-formarray

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!