Igor
Igor

Reputation: 550

how to prevent clicking on a disabled button through the parent component in angular?

I have a generic component app-button which contains a button element.

Button component html

<button [type]="type" [disabled]="isLoading || !!disabled">
    <ng-content></ng-content>
</button>

Button component ts

@Component({
  selector: 'app-button',
  templateUrl: 'views/button.component.html',
  styleUrls: ['styles/button.component.scss']
})
export class ButtonComponent implements OnInit {
  @Input() type: string;
  @Input() color: string;
  @Input() disabled: boolean;
  @Input() class: string;
  isLoading: boolean;
  constructor() {
    this.type = "submit";
  }
}

I added (click) to my component and it works fine. But when I put disabled attribute it disables the button, but the (click) still works when you click on a content.

<app-button (click)="signIn()" [disabled]="true">
    <span>Signin</span>
</app-button>

Upvotes: 2

Views: 3050

Answers (1)

Abel Valdez
Abel Valdez

Reputation: 2408

I Think that your problem is that you are disabling you child component and you have the click event in the parent component

A solution could be moving your (click)="signIn()" to your child component and it will be disable and add an @Output decorator to receive the callback from the child

Child Component html

<button [type]="type" [disabled]="isLoading || !!disabled" (click)="signIn()">
    <ng-content></ng-content>
</button>

Child Component ts

@Component({
  selector: 'app-button',
  templateUrl: 'views/button.component.html',
  styleUrls: ['styles/button.component.scss']
})
export class ButtonComponent implements OnInit {
  @Input() type: string;
  @Input() color: string;
  @Input() disabled: boolean;
  @Input() class: string;
  @Output() callback = new EventEmitter();
  isLoading: boolean;
  constructor() {
    this.type = "submit";
  }

  signIn(){
     this.callback.emit();
  }

}

Parent Component html

<app-button (callback)="signIn()" [disabled]="true">
    <span>Signin</span>
</app-button>

Demo StackBlitz

Upvotes: 2

Related Questions