Can you prevent an Angular component's host click from firing?

后端 未结 3 1539
我寻月下人不归
我寻月下人不归 2020-12-16 13:00

I\'m creating an Angular component that wraps a native

3条回答
  •  误落风尘
    2020-12-16 13:22

    You can use the native add and remove EventListeners. This is in no way a good solution when thinking in angular terms. Also, this won't work if you put disabled attribute in button as it will override eventListeners attached. A disabled class need to be used instead. (Or else wrap button in a span and use template ref #btn from it.)

    StackBlitz

    import { Component, OnInit, OnChanges, HostListener, Input, Output, EventEmitter, SimpleChanges, ElementRef, ViewChild } from '@angular/core';
    
    @Component({
      selector: 'app-my-button',
      template: ``,
      styles: [`button.disabled { opacity:0.5 }`]
    })
    export class MyButtonComponent implements OnInit, OnChanges {
      disableClick = e => e.stopPropagation();
      @Input() isDisabled: boolean;
      @ViewChild('btn') btn: ElementRef;
      constructor() { }
    
      ngOnChanges(changes: SimpleChanges) {
        if(this.isDisabled) {
          this.btn.nativeElement.addEventListener('click', this.disableClick);
        } else {
          this.btn.nativeElement.removeEventListener('click', this.disableClick);
        }
      }
      ngOnInit() {
      }
    
    }
    

提交回复
热议问题