Angular 表单 : 还没有表单控件注册到这个数组

Angular Form : There are no form controls registered with this array yet

我遇到了一个小问题,也许有人可以提供帮助,因为我已经为此工作了一个多小时...

在我的组件文件中,我使用一种方法创建一个表单,然后我使用另一种方法进行 API 调用,return 一些数据并设置创建数组的一个控件。这是我的一些简化代码,只有 ngOnInitconstructor 和相关方法

constructor(public dialogRef: MatDialogRef<EditAccountComponent>,
          @Inject(MAT_DIALOG_DATA) private data,
          private apiService: ApiService,
          private emailUniqueValidator: EmailUniqueValidator) {
            this.user = data;
}

ngOnInit(): void {
    this.editAccountForm = this.createEditUserForm();
    this.getRoles();
}

createEditUserForm(): FormGroup {
    return new FormGroup({
        name: new FormControl(this.user.name, [Validators.required, Validators.max(50)]),
        email: new FormControl(
        this.user.emailAddress,
        [Validators.required, Validators.pattern('^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$')],
        this.emailUniqueValidator.validate.bind(this)
        ),
        companies: new FormControl(this.user.tags.company),
        roles: new FormArray([])
    });
}

getRoles(): any {
        this.apiService.getUserRoles(this.data.id).subscribe(roles => {
        // roles = ['role 1', 'role 2', 'role 3'];
        this.editAccountForm.controls['roles'].setValue(roles);
    });
}

在我的 createEditUserForm 方法中,我使用 new FormArray([]) 创建角色 属性,因为值可以是最多具有 4 个值的字符串数组,例如:['role 1', 'role 2','role 3','role 4'].在我的 getRoles 方法中,我 return 一个字符串数组并尝试将其设置为表单的角色 属性。但是,这给了我一个错误;

"There are no form controls registered with this array yet. If you're using ngModel, you may want to check next tick (e.g. use setTimeout)."

所以我尝试将 .setValue(roles) 更改为 .patchValue(roles)...但这没有用,我还尝试使用 this.apiService.getUserRoles 中的每个值创建一个 FormControls 数组调用,这不起作用...有人可以告诉我如何使用 API 中的字符串数组 return 设置角色表单 属性 的值吗?

您的 FormArray 未正确初始化,并且不包含应在其中设置以下角色的任何 FormControl。您需要使用 Angular documentation If you would like to set them dynamically depend of the quantity of the roles see code under link https://stackblitz.com/edit/angular-6dzav1

中所写的初始值填充它

您需要检查组件是否已渲染并出现在 HTML 上。我遇到了这个问题,在检查值更改时看到它在 ngIf 中。