Amritraj
Amritraj

Reputation: 25

How to render specific tree nodes in Angular Material flat tree based on a node property?

I wanna display specific tree nodes <mat-tree-node> based on a node's nodeAuthorized: boolean property. How can I achieve this since angular does not allow more than 2 structural directives on a single element.

I've tried using the nodeAuthorized property on the only child <div> of <mat-tree-node>, but this renders an empty space between 2 or more tree nodes. Any help would be appreciated?

This is what I've tried but, this leaves an obvious empty space between nodes which I don't want.

<mat-tree-node *matTreeNodeDef="let node; when: hasChild" matTreeNodePadding>
 <div *ngIf="node.treeNode.nodeAuthorized">   
  <button mat-icon-button matTreeNodeToggle>
   <mat-icon class="mat-icon-rtl-mirror">
    {{
       treeControl.isExpanded(node) ? "expand_more" : "chevron_right"
     }}
    </mat-icon>
   </button>

   {{node.treeNode.nodeName}}
 </div>
</mat-tree-node>

Upvotes: 0

Views: 2125

Answers (1)

Amritraj
Amritraj

Reputation: 25

*matTreeNodeDef can be used with <ng-container> which can then be used with another HTML element say <div> and structural directive *ngIf to render specific nodes.

<ng-container *matTreeNodeDef="let node">
    <ng-container *ngIf="node.authorized"> /** node rendering condition goes here */
      <mat-tree-node matTreeNodePadding>
        <button mat-icon-button matTreeNodeToggle>
          <mat-icon class="mat-icon-rtl-mirror">
            {{treeControl.isExpanded(node) ? 'expand_more' : 'chevron_right'}}
          </mat-icon>
        </button>
        {{node.name}}
      </mat-tree-node>
    </ng-container>
  </ng-container>

Upvotes: 1

Related Questions