如何使用 SelectionModel 以编程方式选择材质树节点? [英] How do I programmatically select Material Tree nodes with 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?
推荐答案
要预先选择水果节点,请在 TreeChecklistExample
类的 ngAfterViewInit
中实现以下内容附加的stackblitz示例.
To pre-select the fruits node implement the following in an ngAfterViewInit
for the TreeChecklistExample
class in the attached stackblitz example.
- 这将遍历
treeControl
中的 - 如果
item == 'Fruits'
选择节点并展开 同样,如果
item == 'Groceries'
展开节点,因为它是 Fruits 的父节点.
dataNodes
- This will loop through the
dataNodes
in thetreeControl
- 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屋!