如何使用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?
推荐答案
要预先选择水果节点,请在随附的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
中的 - 如果
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屋!