2017-05-27 104 views
1

我尝试动态添加角色到我的用户/角色应用程序。我有一个Formarray,我可以在编辑视图中显示用户的角色。还有一个按钮用于向用户添加更多角色。但是,当我按下按钮“添加角色”,我得到这个错误信息:Angular 2 Reactive Forms:无法找到路径控制

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); 
} 

Wh我在做错吗?

回答

1

您应该创建一个表单组与Roles如下的控制,

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

    }); 
} 

那么你应该按如下的作用,

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

谢谢你的人!我知道这很容易。但不知道问题是什么。它现在完美 –

+0

高兴地帮助你。你需要什么? – Aravind

+0

多数民众赞成它现在,谢谢=) –