2017-05-27 95 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

多數民衆贊成它現在,謝謝=) –

相關問題