src/app/reactive-form/reactive-form.component.html:47:48 - 错误 TS2531:对象可能为“null”。 src/app/reactive-form/reactive-form.component.ts

问题描述 投票:0回答:1

对象可能为“空”。元素隐式具有“any”类型,因为类型“controls”的表达式不能用于索引类型“AbstractControl”。

“AbstractControl”类型上不存在属性“controls”。

<div class="form-group" formArrayName="skills">
    <ng-container *ngFor="let skill of reactiveForm.get('skills')['controls']; let i = index;">
          <label for="Skills">Skills</label>
          <input type="text">
    </ng-container>
</div>

.ts 文件

reactiveForm!: FormGroup;
ngOnInit(): void {
    this.reactiveForm = new FormGroup({
      // To set default value we need to pass this value instead of null.
      firstname: new FormControl(null, Validators.minLength(4)),
      lastname: new FormControl(null, Validators.required),
      email: new FormControl('[email protected]', [Validators.required, Validators.email]),
      country: new FormControl('Canada'),
      gender: new FormControl('male'),
      hobbies: new FormControl(null),
      skills: new FormArray([
        new FormControl(null),
      ])
    })
  }

  onSubmit() {
    console.log(this.reactiveForm);
  }
}
angular angular-reactive-forms angular-forms formarray form-control
1个回答
0
投票

ts 文件中编写技能的 getter

get skills() {
  return this.reactiveForm.get('skills') as FormArray;
}

以及在 HTML

<div class="form-group" formArrayName="skills">
  <ng-container *ngFor="let skill of skills.controls; let i = index;">
        <label for="Skills">Skills</label>
        <input type="text">
  </ng-container>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.