4

I'm trying to disable an input depending on the value taken from the Component.ts

In my component.ts file I have this value

disName = false;

And in my HTML I have these elements

Name: <input type="text"
             value="name"
             size="15"
             id="name"
             name="firstName"
             [(ngModel)]="aproverFirstName"
             [attr.disable]="disName=='true' ? true : null">

What looking for is that if my value on the component.ts is false, then in the html file the input element should change to disable depending on the value.

I've also tried this [disable]="disName"

I'm using Angular 7, thanks a lot!

3
  • Camila, disName is a boolean, so [attr.disable]="disName ? true : null"> (not put =='true') Commented Sep 30, 2019 at 7:18
  • it's disabled, not disable Commented Oct 29, 2019 at 11:46
  • I have this: [attr.disabled]="!inactive ? true : null" with inactive set as false in the TS file. I use a button to change the value. This works but not on the initial state. When I open page, my input field is editable, only when I change to true and back to false does it disable the field. Any idea how to change this? Commented Jun 22, 2021 at 6:19

3 Answers 3

6

You should do like this:

<input type="text"
             value="name"
             size="15"
             id="name"
             name="firstName"
             [(ngModel)]="aproverFirstName"
             [disabled]="disName">

But, I prefer to use @angular/forms in Angular, Then you can init the form like this:

HTML:

<input type="text"
                 value="name"
                 size="15"
                 id="name"
                 formControlName="firstName">

Typescript:

Init form:

this.sampleForm= this.fb.group({
      firstName: [{ value: '', disabled: true }, Validators.required]
});

Control enable and disable by:

this.sampleForm.controls.firstName.enable();
this.sampleForm.controls.firstName.disable();
Sign up to request clarification or add additional context in comments.

Comments

1

The attribute you're looking for is [disabled].

<input type="text" [disabled]="true" />

Comments

-1

Try this

  <input type="text" [disabled]="!disName">

the condition has to be true.

Are you putting this "input" tag in component.html?

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.