6

I am using Angular Material Tree Control with dynamic data.

Here is the link of complete example:

example is here

It works as mentioned in example. Now i want to enable each node click event and send the (angular expression) bound data in my typescript function.

Can anyone guide me ?

I tried different codes but tree node couldn't be enabled for clicking.

See html :

    <mat-tree [dataSource]="dataSource" [treeControl]="treeControl">
  <mat-tree-node *matTreeNodeDef="let node" matTreeNodePadding>
    <button mat-icon-button disabled ></button>
    {{node.item}}
  </mat-tree-node>
  <mat-tree-node *matTreeNodeDef="let node; when: hasChild" matTreeNodePadding>
    <button mat-icon-button  (click)="applyFilter($event)"
            [attr.aria-label]="'toggle ' + node.filename" matTreeNodeToggle>
      <mat-icon class="mat-icon-rtl-mirror">
        {{treeControl.isExpanded(node) ? 'expand_more' : 'chevron_right'}}
      </mat-icon>
    </button>
    {{node.item}}
    <mat-progress-bar *ngIf="node.isLoading"
                      mode="indeterminate"
                      class="example-tree-progress-bar"></mat-progress-bar>
  </mat-tree-node>
</mat-tree>

I tried this source but still unable to fix it. I tried with stack overflow solutions but it couldn't solve my issue yet.

 ngAfterViewChecked() {
    this.treeNodes.forEach((reference) => {
      if (!this.hasListener.includes(reference.nativeElement)) {
        console.log('* tick');

        this.renderer.listen(reference.nativeElement, 'click', () => {
          this.updateHighlight(reference);
        });
        this.renderer.listen(reference.nativeElement.children.item(0), 'click', () => {
          this.updateHighlight(reference);
        });

        this.hasListener = this.hasListener.concat([reference.nativeElement]);
      }
    });

    this.hasListener = this.hasListener.filter((element) => document.contains(element));
    console.log('*', this.hasListener.length);
  }

1 Answer 1

7

You could wrap your {{node.item}} in a mat-button and bind to the click event from there to pass the node element to your component method.

<mat-tree-node *matTreeNodeDef="let node" matTreeNodePadding>
    <button mat-button (click)="logNode(node)">
      {{node.item}}
    </button>
</mat-tree-node>

Then in your component

 logNode(node){
    console.log(node)
  }
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. it is working when i removed first tree node.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.