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

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

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

3条回答
  •  佛祖请我去吃肉
    2020-12-16 13:38

    You could do the following:

    • Redefine the click event of the component, and emit this event when the button is clicked
    • Set the CSS style pointer-events: none on the component host
    • Set the CSS style pointer-events: auto on the button
    • Call event.stopPropagation() on the button click event handler

    If you need to process the click event of other elements inside of your component, set the style attribute pointer-events: auto on them, and call event.stopPropagation() in their click event handler.

    You can test the code in this stackblitz.

    import { Component, HostListener, Input, Output, ElementRef, EventEmitter } from '@angular/core';
    
    @Component({
      selector: 'my-button',
      host: {
        "[style.pointer-events]": "'none'"
      },
      template: `
        
        Span element`,
      styles: [`button, span { pointer-events: auto; }`]
    })
    export class MyCustomComponent {
    
      @Input() public isDisabled: boolean = false;
      @Output() public click: EventEmitter = new EventEmitter();
    
      onButtonClick(event: MouseEvent) {
        event.stopPropagation();
        this.click.emit(event);
      }
    
      onSpanClick(event: MouseEvent) {
        event.stopPropagation();
      }
    }
    

    UPDATE:

    Since the button can contain HTML child elements (span, img, etc.), you can add the following CSS style to prevent the click from being propagated to the parent:

    :host ::ng-deep button * { 
      pointer-events: none; 
    }
    

    Thanks to @ErikWitkowski for his comment on this special case. See this stackblitz for a demo.

提交回复
热议问题