【问题标题】:How to set value to FormBuilder object in angular 2 Typescript如何在 Angular 2 Typescript 中为 FormBuilder 对象设置值
【发布时间】:2017-02-26 02:57:19
【问题描述】:

我使用了响应式表单验证(模型驱动验证),但无法在下拉更改时将值设置为表单对象

这是我的表单组

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>

更改时我需要设置表单控件值

【问题讨论】:

标签: javascript html angular typescript


【解决方案1】:

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

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

或:

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

【讨论】:

  • 你可以请这个
  • Name = new FormControl({ value:'', disabled: true }, [Validators.required, Validators.maxLength(10) ]);我想在更改时禁用 false 你能告诉我解决方案吗...
  • 你也可以使用“as”const fc = this.AMform.controls['Name'] as FormControl; fc.setValue('new value');
【解决方案2】:

使用 FormGroup 对象的 patchValue 方法。

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

【讨论】:

    【解决方案3】:

    使用setValue,您需要指定所有 FormControls:

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

    使用patchValue,您可以只指定一个您需要:

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

    Here你可以多读一点。

    【讨论】:

      猜你喜欢
      • 2019-07-22
      • 2015-12-30
      • 1970-01-01
      • 1970-01-01
      • 2023-01-24
      • 1970-01-01
      • 2016-07-31
      • 2021-08-15
      • 2021-09-08
      相关资源
      最近更新 更多