Md Junaid Alam
Md Junaid Alam

Reputation: 1349

Angular Reactive forms set values with disabled attribute after form is initialized

I have created one form.

HTML Code :

<form [formGroup]="form">
  <input formControlName="name"/>
  <input formControlName="description"/>
  <input formControlName="category"/>
  <input formControlName="type"/>
</form>

Below is the code to initialize form, setting initial value as empty:

form: FormGroup;
constructor(private fb: FormBuilder) { }
ngOnInit() {
  this.initForm();
}

private initForm() {
  this.form = this.fb.group({
      name: ['', Validators.required],
      description: [''],
      category: ['', Validators.required],
      type: ['',  Validators.required],
  });
}

On certain condition the form needs to be filled with data received form a API. Once the data is received below code is executed :

// data received from API
if(data){
 this.form = this.fb.group({
  name: [{value: data.name, disabled: true}],
  description: [{value: data.description, disabled: true}],
  category: [{value: data.category, disabled: true}],
  type: [{value: data.type, disabled: true}]
 });
}

In above case, values are getting updated correctly, but the controls are not getting disabled.

I also tried setValue:

this.form.setValue({
  name: {value: data.name, disabled: true},
  description: {value: data.description, disabled: true},
  category: {value: data.category, disabled: true},
  type: {value: data.type, disabled: true}
});

In above case, the values are filled with [object Object].

How can I set the field value and set disabled attribute at same time?

Upvotes: 0

Views: 1856

Answers (1)

kvetis
kvetis

Reputation: 7331

Why don't you just setValue and disable the whole form?

this.form.setValue(data);
this.form.disable();

Upvotes: 1

Related Questions