Skip to content

feat(tree): typescript/strong typing of nodes #30502

Open
@aceArt-GmbH

Description

@aceArt-GmbH

Feature Description

Currently *matTreeNodeDef types the resulting variable as any:

Image

Use Case

enable you to build web apps with confidence!

The lack of strong typing is really problematic for bigger projects, and it feels like a downgrade in developer experience compared to custom build trees.

Further motivation for this has been described in:

#16273
angular/angular#28731
https://nartc.me/blog/typed-mat-cell-def/
#22290

Workaround copied from #22290:

import { Directive, input } from '@angular/core';
import { MatTree, MatTreeNodeDef } from '@angular/material/tree';

@Directive({
   selector: '[matTreeNodeDef]',
   providers: [
      { provide: MatTreeNodeDef, useExisting: TypeSafeMatTreeNodeDefDirective },
   ],
})
export class TypeSafeMatTreeNodeDefDirective<T> extends MatTreeNodeDef<
   NoInfer<T>
> {
   readonly matTreeNodeDefTree = input.required<MatTree<T>>();

   static ngTemplateContextGuard<T>(
      dir: TypeSafeMatTreeNodeDefDirective<T>,
      ctx: any,
   ): ctx is { $implicit: T; index: number } {
      return true;
   }
}
-<mat-tree [dataSource]="dataSource" [childrenAccessor]="childrenAccessor">
+<mat-tree #tree [dataSource]="dataSource" [childrenAccessor]="childrenAccessor">
...
-<mat-tree-node *matTreeNodeDef="let node;" matTreeNodePadding>
+<mat-tree-node *matTreeNodeDef="let node; tree: tree" matTreeNodePadding>

Metadata

Metadata

Assignees

No one assigned

    Labels

    P3An issue that is relevant to core functions, but does not impede progress. Important, but not urgentarea: cdk/treefeatureThis issue represents a new feature or feature request rather than a bug or bug fix

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions