简体   繁体   中英

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!

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

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

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

Try this

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

the condition has to be true.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM