Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

This is my 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

<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

like image 255
coder Avatar asked Oct 17 '16 07:10

coder


2 Answers

You can achievie that by invoking setValue method on your FormControl object:

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

or:

this.Name.setValue("new value");
like image 83
Maciej Treder Avatar answered Nov 02 '22 04:11

Maciej Treder


Using setValue you need to specify all the FormControls:

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

Using patchValue you can specify just the one you need:

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

Here you can read a little bit more.

like image 27
hestellezg Avatar answered Nov 02 '22 04:11

hestellezg