如何使用SelectionModel以编程方式选择“材料树"节点? [英] How do I programmatically select Material Tree nodes with SelectionModel?

查看:93
本文介绍了如何使用SelectionModel以编程方式选择“材料树"节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一棵带有复选框的树(在这里使用Material的示例).我希望开始检查水果节点.如何检查这些节点?

I have a tree with checkboxes (let's use Material's example here). I'd like the fruit nodes to begin checked. How do I check those nodes?

我看到SelectionModel有一个select()方法,该示例传递了一个节点.但是在示例中,树所构成的数据是TodoItemNode的数组,但是SelectionModel包含TodoItemFlatNode.示例中的transformer方法可以拉平"我的节点(即,将TodoItemNode转换为TodoItemFlatNode),但这将返回一个新实例.

I see that SelectionModel has a select() method that the example passes a node. But in the example, the data the tree is made of is an array of TodoItemNode, but the SelectionModel contains TodoItemFlatNode. The transformer method in the example can "flatten" my node (ie. convert TodoItemNode to TodoItemFlatNode), but that would return a new instance.

如何以编程方式选择mat-tree复选框以匹配我的数据?

How can I programmatically select mat-tree checkboxes to match my data?

推荐答案

要预先选择水果节点,请在随附的stackblitz示例中的TreeChecklistExample类的ngAfterViewInit中实现以下内容.

To pre-select the fruits node implement the following in an ngAfterViewInit for the TreeChecklistExample class in the attached stackblitz example.

  • 这将循环遍历treeControl
  • 中的dataNodes
  • 如果item == 'Fruits'选择节点并展开
  • 如果item == 'Groceries'扩展节点,因为它是Fruits的父级.

  • This will loop through the dataNodes in the treeControl
  • If item == 'Fruits' select node and expand
  • Also if item == 'Groceries' expand node as it is the parent of Fruits.

ngAfterViewInit() {
    for (let i = 0; i < this.treeControl.dataNodes.length; i++) {
      if (this.treeControl.dataNodes[i].item == 'Fruits') {
        this.todoItemSelectionToggle(this.treeControl.dataNodes[i]);
        this.treeControl.expand(this.treeControl.dataNodes[i])
      }
      if (this.treeControl.dataNodes[i].item == 'Groceries') {
        this.treeControl.expand(this.treeControl.dataNodes[i])
      }
    }
  }

Stackblitz

https://stackblitz. com/edit/angular-j2nf2r?embed = 1& file = app/tree-checklist-example.html

这篇关于如何使用SelectionModel以编程方式选择“材料树"节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆