如何在 angular 2 Typescript 中为 FormBuilder 对象设置值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40081065/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set value to FormBuilder object in angular 2 Typescript
提问by coder
I am used Reactive form Validation(Model driven validation) but cant set the value to form object on Dropdown change
我使用了反应式表单验证(模型驱动验证),但无法在下拉更改时将值设置为表单对象
This is my 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
}
This is My html page
这是我的 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>
On change i need to set the formcontrol value
在更改时,我需要设置 formcontrol 值
回答by Maciej Treder
You can achievie that by invoking setValue
method on your FormControl
object:
您可以通过setValue
在FormControl
对象上调用方法来实现:
(<FormControl> this.AMform.controls['Name']).setValue("new value");
or:
或者:
this.Name.setValue("new value");
回答by jmachnik
Use patchValue method of your FormGroup object.
使用 FormGroup 对象的 patchValue 方法。
onAccntChange(event: Event) {
this.AMform.patchValue({yourControl: studentModelValue})
}
回答by estellezg
Using setValue
you need to specify allthe FormControls:
使用setValue
你需要指定所有的 FormControls:
this.AMform.setValue({'Name':'val1', 'Address':'val2'})
Using patchValue
you can specify just the oneyou need:
使用patchValue
您可以仅指定您需要的一个:
this.AMform.patchValue({'Name':'val1'})
Hereyou can read a little bit more.
在这里你可以多读一点。