微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

原文地址:https://www.jb51.cc/js/155608.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐