Angular 2 反应形式:找不到带路径的控件

Angular 2 Reactive Forms: Cannot find control with path

我尝试将角色动态添加到我的 User/Roles-application。我有一个 Formarray,我可以在编辑视图中显示用户的角色。还有一个用于向用户添加更多角色的按钮。但是当我按下按钮 "Add Role" 时,我得到了这个错误信息:

ERROR Error: Cannot find control with path: 'rolesArr -> 1 -> name'

在此示例中,我尝试向要创建的用户添加多个角色。

这是我的代码:

用户-edit.component.html(摘录)

<div formArrayName="rolesArr" >
<div class="row">
    <div class="col-md-10 col-md-offset-2">
        <button class="btn btn-default"
                type="button"
                (click)="addRole()">Add Role
        </button>
    </div>
</div>
<br>
<div *ngFor="let role of roles.controls; let i=index">
    <div [formGroupName]="i">

        <div class="form-group">
            <label class="col-md-2 control-label" [attr.for]="i">Role</label>

            <div class="col-md-8">
                <input class="form-control"
                        [id]="i" 
                        type="text" 
                        placeholder="Role" 
                        formControlName="name" />
            </div>
        </div>
    </div>
</div>

用户-edit.component.ts(摘录)

addRole() {
    this.roles.push(this.fb.group(new Roles()));
}

ngOnInit(): void {

    this.userForm = this.fb.group({
        username: ['', [Validators.required, Validators.minLength(3)]],
        firstname: ['', [Validators.required, Validators.minLength(3)]],
        lastname: ['', [Validators.required, Validators.minLength(3)]],
        password: ['', [Validators.required, Validators.minLength(10)]],
        rolesArr: this.fb.array([])
    });

    this.sub = this.activeRoute.params.subscribe(
        params => {
            let id = +params['id']; //converts string'id' to a number
            this.getUser(id);
        }
    );
}
getUser(id: number) {
        this.userService.getUser(id).subscribe(
                user => this.onUserRetrieved(user)
            );
}
onUserRetrieved(user: User): void {
    console.log("OnUserRetrieved: " + user.firstname);
    if (this.userForm) {
        this.userForm.reset();
    }
    this.users = user;

    if (this.users.id === 0) {
        this.pageTitle = 'Add User';
    } else {
        this.pageTitle = `Edit User: ${this.users.username}`;
    }

    //Update the data on the form
    this.userForm.patchValue({
        username: this.users.username,
        firstname: this.users.firstname,
        lastname: this.users.lastname,
        password: this.users.password
    });

    const roleFGs = this.users.roles.map(roles => this.fb.group(roles));
    const roleFormArray = this.fb.array(roleFGs);
    this.userForm.setControl('rolesArr', roleFormArray);
}

我做错了什么?

您应该创建一个带有 Roles 控件的表单组,如下所示,

createRole() :  FormGroup {
    return this.fb.group({
            name: '',
            type: '',

    });
}

那么你应该按如下方式推送角色,

addRole() {
    this.roles.push(this.createRole());
}

虽然 Aravind 的 有效,但您仍然可以做与现在完全相同的事情:

addRole() {
    this.roles.push(this.fb.group(new Roles()));
}

但是控件需要 class 中的属性的默认值(这正是 Aravind 的解决方案所做的,它创建了一个具有默认值的对象)

因此,如果您当前的 Roles class 看起来像这样:

export class Roles {
    public name: string;
    public type: string;
}

您应该像这样添加默认值:

export class Roles {
    public name: string = '';
    public type: string = '';
}

这允许 angular 找到您的属性作为控件的

附加信息: https://angular.io/guide/reactive-forms#use-formarray-to-present-an-array-of-formgroups