4

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

Edric
  • 24,639
  • 13
  • 81
  • 91
gothaf
  • 218
  • 4
  • 14

2 Answers2

8

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) );
  } 
Alex Beugnet
  • 4,003
  • 4
  • 23
  • 40
4

You need to typecast 'EventTarget' to Element, change function as follows,

private _isExpansionIndicator(target: EventTarget): boolean {
    const expansionIndicatorClass = 'mat-expansion-indicator';
    return ((<Element>target).classList && (<Element>target).classList.contains(expansionIndicatorClass) );
} 
Plochie
  • 3,944
  • 1
  • 17
  • 33