0
votes

I have a drop down in Angular reactive form. I want to disable it on select. But when i use the [disabled]='' attribute directly get this error.

Typescript

// Angular Reactive form validation
this.createform = this.formBuilder.group({ENT_TYP_PSD: ''});

HTML

<div class="form-group row">
  <label class="col-md-3" for="ENT_TYP_PSD">Type of Natural or Legal Person </label>
  <p-dropdown class="col-md-4" name="ENT_TYP_PSD" [options]="parentEntities" optionLabel="EntityTypeName"
    placeholder="Please select" (onChange)="entityTypeChanged($event)" formControlName="ENT_TYP_PSD" [disabled]='disableEntityType'>
  </p-dropdown>
</div>

Error Message:-

It looks like you're using the disabled attribute with a reactive form directive. If you set disabled to true when you set up this control in your component class, the disabled attribute will actually be set in the DOM for you. We recommend using this approach to avoid 'changed after checked' errors.

  Example:    form = new FormGroup({  first: new FormControl({value: 'Nancy', disabled: true}, Validators.required),
last: new FormControl('Drew', Validators.required)   });

And when I use this in typescript, I can't get this field ENT_TYP_PSD value at all in the this.createform.value.

this.createform.controls['ENT_TYP_PSD'].disable(true)
1
try using this.createform.getRawValue()Sarthak Aggarwal
At the time of building the form-group there is only two form-controls are there. That's why you couldn't get it.. can you please add your code snippet here?Madhankumar
@SarthakAggarwal. Many thanks, mate. that helpedJay

1 Answers

1
votes

The error means you shouldn't use the disabled attribute. Instead, you should programmatically set the disabled state of the input, so that Angualr can keep track of it.

Try removing the attribute and using getter/setter/variable combo :

_disableEntityType: boolean
get disableEntityType() { return !!this._disableEntityType; }
set disableEntityType(value: boolean) {
  this._disableEntityType = value;
  this.createForm.get('ENT_TYP_PSD')[value ? 'disable' : 'enable']();
}

For the creation :

this.createform = this.formBuilder.group({ENT_TYP_PSD: {
  value: '',
  disabled: this.disableEntityType
}});