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

1

3 Answers 3

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");
Sign up to request clarification or add additional context in comments.

3 Comments

can u pls this one
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...
You can also use "as" const fc = this.AMform.controls['Name'] as FormControl; fc.setValue('new value');
6

Use patchValue method of your FormGroup object.

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.