2016-10-17 73 views
5

我使用的反應形式驗證(模型驅動的驗證),但不能形成集上下拉改變對象的值如何設置值FormBuilder對象角2打字稿

這是我Formgroup

studentModel:StudenModel 
AMform: FormGroup; 
Name = new FormControl("", Validators.required); 
Address = new FormControl("", Validators.maxLength(16)); 

constructor(fb: FormBuilder){  
    this.AMform = fb.group({ 
    "Name": this.Code, 
    "Address": this.Abbrev, 
    }); 
} 
onAccntChange(event: Event) { 
    // set the value from Class Model 
    //// this.studentModel 
    // how to set this.studentModel value to form 
}  

這是我的HTML頁面

<form [formGroup]="AMform" (ngSubmit)="submit()"> 
    <select (change)="onAccntChange($event)" class="form-control" [disabled]="ddlActivity" formControlName="AccountManagerID"> 
     <option value="0">Select</option> 
     <option *ngFor="let item of allStudent" value={{item.StudentID}}> 
      {{item.Name}} 
     </option> 
    </select> 

    <div class="col-sm-9"> 
     <input type="text" class="form-control" formControlName="Name"> 
    </div> 
    <div [hidden]="Name.valid || Code.pristine" class="error"> Name is required </div> 

    <div class="col-sm-9"> 
     <input type="text" class="form-control" formControlName="Address"> 
    </div> 
    <div [hidden]="Address.valid || Address.pristine" class="error">Address is required </div> 

    <button type="submit" class="btn btn-warning "><i class="fa fa-check-square"></i> Save</button> 
</form> 

在變化,我需要設置formcontrol值

回答

10

可以achievie通過調用您的FormControl對象setValue方法:

(<FormControl> this.AMform.controls['Name']).setValue("new value"); 

或:

this.Name.setValue("new value"); 
+1

感謝它的工作.. – coder

+1

可以使用這一個 – coder

+0

Name = new FormControl({value:'',disabled:true},[Validators.required,Validators.maxLength(10)]); 我想禁用虛假的變化 可以告訴我解決方案... – coder

3

您FormGroup對象的使用方法patchValue。

onAccntChange(event: Event) { 
    this.AMform.patchValue({yourControl: studentModelValue}) 
    } 
+0

謝謝,這是一個很好的解決方案... :) – coder

0

使用setValue需要指定所有的FormControls:

this.AMform.setValue({'Name':'val1', 'Address':'val2'}) 

使用patchValue你可以指定你需要的一個:

this.AMform.setValue({'Name':'val1'}) 

Here你可以讀一點多一點。