Home > Software design >  How to make button disable with true or false with property binding and without binding?
How to make button disable with true or false with property binding and without binding?

Time:03-11

    import { Component } from '@angular/core';  
@Component({  
    selector: 'my-app',  
    template: `<div>  
    <button [disabled]='isDisabled'>click</button>  
                     </div>`  
})  
export class AppComponent {  
isDisabled= false;  
}

Above angular code making button enable but below code without any data binding not enabling button regardless of true or false. please help me to understand what is wrong.

import { Component } from '@angular/core';  
@Component({  
    selector: 'my-app',  
    template: `<div>  
    <button disabled=false>Disable me</button>  
                     </div>`  
})  
export class AppComponent {  

} 

CodePudding user response:

There is difference between [disabled]="isDisabled" and disabled="false"

[disabled]="isDisabled" - you are changing property directly in the DOM, through Angular, that's why you should pass true or false

disabled="false" - it's just simple html attribute, you can pass whatever you want, event disabled="1", it will be counted as true anyway, if you want to enable button you should delete this attribute from html

CodePudding user response:

If you don't use the square brackets, it will be treated as disabled, which is the intended use of this attribute:

<button disabled>Disabled</button>

You would have to add/remove the attribute to enable/disable the button with Javascript:

<button>Enabled</button>

Since you are in Angular, it's best to use square brackets on disabled and assign a boolean to it:

<button [disabled]="true">Disabled</button>
<button [disabled]="false">Enabled</button>
  • Related