简体   繁体   English

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

[英]How to set value to FormBuilder object in angular 2 Typescript

I am used Reactive form Validation(Model driven validation) but cant set the value to form object on Dropdown change 我使用了Reactive form Validation(模型驱动的验证),但是无法在Dropdown更改时将值设置为form对象

This is my Formgroup 这是我的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值

You can achievie that by invoking setValue method on your FormControl object: 您可以通过在FormControl对象上调用setValue方法来实现:

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

or: 要么:

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

Use patchValue method of your FormGroup object. 使用FormGroup对象的patchValue方法。

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

Using setValue you need to specify all the FormControls: 使用setValue您需要指定所有 FormControls:

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

Using patchValue you can specify just the one you need: 使用patchValue您可以指定所需的那个

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

Here you can read a little bit more. 在这里你可以阅读更多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM