0

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?

3
  • To set value and disable at once, you could try name: [{value: data.name, disabled: true}, Validators.required], Commented Mar 25, 2020 at 13:46
  • 1
    your code works, see an stackblitz stackblitz.com/edit/…, you only need take care if the "form" has no value, using in .html <form *ngIf="form"...> to avoid initial errors Commented Mar 25, 2020 at 16:08
  • @Eliseo, Thanks, adding ngIf="form", fixed my issue. Commented Mar 25, 2020 at 16:52

1 Answer 1

1

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

this.form.setValue(data);
this.form.disable();
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I also thought of doing this. I wanted to know whether we can achieve this at once (setting the value and disabling the control).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.