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

cod*_*der 9 html javascript typescript angular

我使用了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
}    
Run Code Online (Sandbox Code Playgroud)

这是我的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>
Run Code Online (Sandbox Code Playgroud)

在更改时,我需要设置formcontrol值

Mac*_*der 13

您可以通过调用对象setValue上的方法来实现FormControl:

  (<FormControl> this.AMform.controls['Name']).setValue("new value");
Run Code Online (Sandbox Code Playgroud)

要么:

this.Name.setValue("new value");
Run Code Online (Sandbox Code Playgroud)


jma*_*nik 6

使用FormGroup对象的patchValue方法。

 onAccntChange(event: Event) {
    this.AMform.patchValue({yourControl: studentModelValue})
    }
Run Code Online (Sandbox Code Playgroud)


est*_*ezg 5

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

this.AMform.setValue({'Name':'val1', 'Address':'val2'})
Run Code Online (Sandbox Code Playgroud)

使用patchValue您可以指定您需要的一个

this.AMform.patchValue({'Name':'val1'})
Run Code Online (Sandbox Code Playgroud)

在这里你可以多读一点。