Search code examples
angulartypescriptcomponents

How do I add [disabled] = "true" to the button tag in Angular


I am writing html tags as a component myself. I want to disable the login button because the inputs I received with username and password are blank when the page is opened. Can't you find how to do it because I created my own button component, can you help?

button.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'ng-idea-button, button[ng-idea-button], a[ng-idea-button]',
  inputs: ["icon"],
  template: `
    <ng-idea-icon *ngIf="icon" [name]="icon"></ng-idea-icon>
    <span><ng-content></ng-content></span>
  `,
  host: {
    'class': 'btn btn-primary',
    '[class.btn-icon]': 'icon'
  }
})
export class ButtonComponent implements OnInit {

  public icon?: string | null;

  constructor() {}

  ngOnInit(): void {
  }

}

login.component.html

<button ng-idea-button class="text-center" type="submit" [disabled]="false">Login</button>
<button ng-idea-button class="text-center" type="submit" [disabled]="true">Login</button>

Solution

  • You were close, use [disabled]="condition" instead of disabled="condition"

    The latter does not work, because you're effectively just passing a string to the disabled property, and since any non empty string equates to true, your buttons were both disabled.

    Demo: https://stackblitz.com/edit/angular-disabled-custom-button