9

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

Maciej Treder
  • 11,866
  • 5
  • 51
  • 74
coder
  • 829
  • 3
  • 9
  • 13
  • Does this answer your question? [Manually Set Value for FormBuilder Control](https://stackoverflow.com/questions/35039610/manually-set-value-for-formbuilder-control) – Vibhor Dube Jun 03 '20 at 16:11

3 Answers3

15

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");
Maciej Treder
  • 11,866
  • 5
  • 51
  • 74
  • 1
    can u pls this one – coder Oct 17 '16 at 10:32
  • Name = new FormControl({ value:'', disabled: true }, [Validators.required, Validators.maxLength(10) ]); i want to disabled false on change can u pls tell me the solution... – coder Oct 17 '16 at 10:35
  • You can also use "as" `const fc = this.AMform.controls['Name'] as FormControl; fc.setValue('new value'); ` – Pian0_M4n Sep 28 '17 at 14:06
6

Use patchValue method of your FormGroup object.

 onAccntChange(event: Event) {
    this.AMform.patchValue({yourControl: studentModelValue})
    }
jmachnik
  • 1,120
  • 9
  • 19
5

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.

hestellezg
  • 3,309
  • 3
  • 33
  • 37