Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable an input dynamically with Angular 7

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!

like image 412
Camila Campos Tellez Avatar asked Nov 01 '25 05:11

Camila Campos Tellez


2 Answers

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();
like image 133
Tran Son Hoang Avatar answered Nov 02 '25 19:11

Tran Son Hoang


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

<input type="text" [disabled]="true" />
like image 30
jdgower Avatar answered Nov 02 '25 21:11

jdgower