0

I have a form and i want to disable one of my inputs on a condition.

<mat-form-field>
    <input matInput formControlName="domain" [disabled]="!is_staff && recipients[selectedIndex].verified">
</mat-form-field>

As you can see I want that whenever condition !is_staff && recipients[selectedIndex].verified happened, input be disabled.

But disable attribute is not working!

1

2 Answers 2

3

When it comes to reactive forms, it is not a good practice to disabled FormControls by directly manipulating the DOM. What you did on your code will essentially result in the following warning:

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)
  });

Instead, you should be using the disabled property, as defined by the AbstractControl class. This is what you should be doing:

this.yourForm = this.fb.group({
    domain: [{value: null, disabled: !this.is_staff && this.recipients[selectedIndex].verified},
});
Sign up to request clarification or add additional context in comments.

Comments

2

There is another way to disable a field. Get the particular form's control, and then invoke the disable().

For example: this.form.control.first_name.disable()

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.