Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EventTarget is not able to access classList

I am trying to make an expansion panel expand only when clinking the arrow, but when I try to compile it, this function

private _isExpansionIndicator(target: EventTarget): boolean {
    const expansionIndicatorClass = 'mat-expansion-indicator';
    return (target.classList && target.classList.contains(expansionIndicatorClass) );
  } 

returns the following error:

"Property 'classList' does not exist on type 'EventTarget'"

Any clues how do I get past this error or do you know any other workaround to acheive the same functionality?

I got it working on stackblitz with no errors... https://stackblitz.com/edit/basic-material-e6sh1r

like image 994
gothaf Avatar asked Oct 25 '25 11:10

gothaf


1 Answers

Using console.log({event}); and console.log({target});, you can see the following :

  • The EventTarget is actually MouseEvent, and the target property is not of a fixed type. You can see this post to know more on the subject : SO Post
  • Since the target element is a span, you can use with TypeScript the HTMLSpanElement type to help you for that.

Here is imo a cleaner solution of what is proposed as an alternative answer :

  expandPanel(matExpansionPanel: any, event: MouseEvent) {
    console.log({event});

    if (!this._isExpansionIndicator(event.target as HTMLSpanElement)) {
      matExpansionPanel.close();
    }
  }

   private _isExpansionIndicator(target: HTMLSpanElement): boolean {
    console.log({target});
    const expansionIndicatorClass = 'mat-expansion-indicator';
    return (target.classList && target.classList.contains(expansionIndicatorClass) );
  } 
like image 122
Alex Beugnet Avatar answered Oct 27 '25 06:10

Alex Beugnet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!