How to set a value for a FormBuilder object in angular 2 Typescript

I am using Reactive Form Validation (validation using a model), but I cannot set the value to create an object when the drop-down list changes

This is my group of forms.

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

 <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> 

When changing, I need to set formcontrol value

+6
source share
3 answers

You can achieve this by calling the setValue method on your FormControl object:

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

or

 this.Name.setValue("new value"); 
+10
source

Use the patchValue method for the FormGroup object.

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

Using setValue you need to specify all FormControls:

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

Using patchValue you can specify only what you need:

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

You can read a little more here.

+1
source

Source: https://habr.com/ru/post/1258316/


All Articles