javascript – 如何在angular 2 Typescript中为FormBuilder对象设置值

我使用了Reactive form Validation(模型驱动的验证),但是无法在Dropdown更改时将值设置为form对象

这是我的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值

解决方法

您可以通过在FormControl对象上调用setValue方法来实现:
(<FormControl> this.AMform.controls['Name']).setValue("new value");

要么:

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

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...