我尝试将角色动态添加到我的用户/角色应用程序。我有一个 Formarray,我可以在编辑视图中显示用户的角色。还有一个用于向用户添加更多角色的按钮。但是当我按下“添加角色”按钮时,我收到了以下错误消息:
ERROR 错误:找不到带有路径的控件:'rolesArr -> 1 -> name'
在此示例中,我尝试向要创建的用户添加多个角色。
这是我的代码:
users-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>
users-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);
}
我究竟做错了什么?