androidGenX
androidGenX

Reputation: 1148

Angular mat tree on matTreeNodeDef iteration not able to get index as of ngfor

I have an angular material tree. On which i have a code like below

<mat-tree-node *matTreeNodeDef="let node; let idx=index">
  {{node.filename}}::{{idx}}
</mat-tree-node>

Here idx not populating

Upvotes: 11

Views: 8010

Answers (4)

mr.vea
mr.vea

Reputation: 454

you will need to add index to the node with a transform function like: https://stackoverflow.com/a/57142368/11692089

Upvotes: 1

IAfanasov
IAfanasov

Reputation: 4993

Depending on the task, the css counters could be a solution

Upvotes: 0

T. Sunil Rao
T. Sunil Rao

Reputation: 1247

I'm afraid *matTreeNodeDef is not same as *ngFor directive.

*matTreeNodeDef directive accepts 2 Inputs.

First being TreeNode<T> which can be defined as

<mat-tree-node *matTreeNodeDef="let node">
  ...
</mat-tree-node>

where node represents the TreeNode object.

Second being matTreeNodeDefWhen which is a function to filter the Tree nodes and can be defined as

HTML

<mat-tree-node *matTreeNodeDef="let node; when hasChild">
  ...
</mat-tree-node>

TS

hasChild = (_: number, node: FlatNode) => node.expandable;  // returns a boolean value

Generally speaking, a tree structure does not have an index.

Reference: https://material.angular.io/components/tree/api#MatTreeNodeDef

Upvotes: 6

ch3rr1
ch3rr1

Reputation: 1

I think it's not populating because you are not iterating. The let node; only declares node as the data source. Try let node of nodes or ngFor="let node of node; index as idx".

Upvotes: 0

Related Questions