gpt4 book ai didi

Angular Material Tree 不显示填充数组的子元素

转载 作者:行者123 更新时间:2023-12-05 02:14:11 26 4
gpt4 key购买 nike

我试图在用户展开节点时动态加载子节点。

问题是当我填充子数组时,mat-tree 不显示子项。如果我使用简单的 *ngFor 显示相同的数据,当子数组添加了元素时,它会显示它们。

我这里有一个工作示例:stackblitz example这是代码和html

    import {NestedTreeControl} from '@angular/cdk/tree';
import {Component} from '@angular/core';
import {MatTreeNestedDataSource} from '@angular/material/tree';


export class PropertyLevel {
constructor(
public code : string,
public hasSubLevels: boolean,
public subproperties : PropertyLevel[]
){}
}

@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
nestedTreeControl: NestedTreeControl<PropertyLevel>;
nestedDataSource: MatTreeNestedDataSource<PropertyLevel>;

constructor() {
this.nestedTreeControl = new NestedTreeControl<PropertyLevel>(this._getChildren);
this.nestedDataSource = new MatTreeNestedDataSource();

this.nestedDataSource.data = [
new PropertyLevel( '123', false, []),
new PropertyLevel( '345', true, [
new PropertyLevel( '345.a', false, null),
new PropertyLevel( '345.b', true, []),
]),
new PropertyLevel( '567', false,[]),
];
}

hasNestedChild = (_: number, nodeData: PropertyLevel) => nodeData.subproperties;

private _getChildren = (node: PropertyLevel) => node.subproperties;

expandToggle(node: PropertyLevel, isExpanded: boolean): void {
if (node.subproperties && node.subproperties.length == 0) {
if(node.code == '123') {
node.subproperties.push(new PropertyLevel('123.a', false, null))
}
else if(node.code == '567') {
node.subproperties.push(new PropertyLevel('567.a', false, null));
node.subproperties.push(new PropertyLevel('567.b', false, null));
node.subproperties.push(new PropertyLevel('567.c', false, null));
}
}
}
}

html

    <mat-tree [dataSource]="nestedDataSource" [treeControl]="nestedTreeControl" class="example-tree">
<mat-tree-node *matTreeNodeDef="let node" matTreeNodeToggle>
<li class="mat-tree-node">
<button mat-icon-button disabled></button>
{{node.code}}
</li>
</mat-tree-node>

<mat-nested-tree-node *matTreeNodeDef="let node; when: hasNestedChild">
<li>
<div class="mat-tree-node">
<button mat-icon-button matTreeNodeToggle
(click)="expandToggle(node, nestedTreeControl.isExpanded(node))"
[attr.aria-label]="'toggle ' + node.filename">
<mat-icon class="mat-icon-rtl-mirror">
{{nestedTreeControl.isExpanded(node) ? 'expand_more' : 'chevron_right'}}
</mat-icon>
</button>
{{node.code}}
</div>
<ul [class.example-tree-invisible]="!nestedTreeControl.isExpanded(node)">
<ng-container matTreeNodeOutlet></ng-container>
</ul>
</li>
</mat-nested-tree-node>
</mat-tree>
<div>
<ul>
<li *ngFor="let node of nestedDataSource.data">
{{node.code}}<br />
<ul>
<li *ngFor="let subnode of node.subproperties">
{{subnode.code}}
</li>
</ul>
</li>
</ul>
</div>

最佳答案

这个故事的寓意(如果我错了请纠正我)是在 Angular 与 Angularjs 中,或者至少在 Material Tree 中,开发人员必须提供变化事件,而不是自动连接所有的变化检测,这减少了很多幕后对象创建,使 Angular 更快、更精简。

因此,解决方案是不为 child 使用数组,而是使用 BehaviorSubject,并向类中添加一个方法以添加 addChild。

我回到带有嵌套节点的树 (https://material.angular.io/components/tree/examples) 示例 (https://stackblitz.com/angular/ngdvblkxajq),并调整了 FileNode 类并添加了 addChild 和 addChildren 方法

export class FileNode {
kids: FileNode[] = [];
children:BehaviorSubject<FileNode[]> = new BehaviorSubject<FileNode[]>(this.kids);
filename: string;
type: any;
addChild(node:FileNode):void {
this.kids.push(node);
this.children.next(this.kids);
}
addchildren(nodes:FileNode[]) {
this.kids = this.kids.concat(this.kids, nodes);
this.children.next(this.kids);
}
}

然后我更改了 buildFileTree 中设置子项的行,改为调用 addChildren。 node.children = this.buildFileTree(value, level + 1) 变成了 node.addchildren(this.buildFileTree(value, level + 1))

我还添加了一个方法,我可以通过单击按钮调用该方法来将子项添加到图片节点以进行测试。

    addPictureFile():void {
var picNode = this.data.find((node) => node.filename == 'Pictures');
var newNode = new FileNode();
newNode.filename = 'foo';
newNode.type = 'gif';
picNode.addChild(newNode);
}

现在,Material Tree 确实检测到我在 children 中的变化并进行了 self 更新。工作示例 https://stackblitz.com/edit/angular-addchildtonestedtree

完整、更新的 ts 文件:

import {NestedTreeControl} from '@angular/cdk/tree';
import {Component, Injectable} from '@angular/core';
import {MatTreeNestedDataSource} from '@angular/material/tree';
import {BehaviorSubject} from 'rxjs';

/**
* Json node data with nested structure. Each node has a filename and a value or a list of children
*/
export class FileNode {
kids: FileNode[] = [];
children:BehaviorSubject<FileNode[]> = new BehaviorSubject<FileNode[]>(this.kids);
filename: string;
type: any;
addChild(node:FileNode):void {
this.kids.push(node);
this.children.next(this.kids);
}
addchildren(nodes:FileNode[]) {
this.kids = this.kids.concat(this.kids, nodes);
this.children.next(this.kids);
}
}

/**
* The Json tree data in string. The data could be parsed into Json object
*/
const TREE_DATA = JSON.stringify({
Applications: {
Calendar: 'app',
Chrome: 'app',
Webstorm: 'app'
},
Documents: {
angular: {
src: {
compiler: 'ts',
core: 'ts'
}
},
material2: {
src: {
button: 'ts',
checkbox: 'ts',
input: 'ts'
}
}
},
Downloads: {
October: 'pdf',
November: 'pdf',
Tutorial: 'html'
},
Pictures: {
'Photo Booth Library': {
Contents: 'dir',
Pictures: 'dir'
},
Sun: 'png',
Woods: 'jpg'
}
});

/**
* File database, it can build a tree structured Json object from string.
* Each node in Json object represents a file or a directory. For a file, it has filename and type.
* For a directory, it has filename and children (a list of files or directories).
* The input will be a json object string, and the output is a list of `FileNode` with nested
* structure.
*/
@Injectable()
export class FileDatabase {
dataChange = new BehaviorSubject<FileNode[]>([]);

get data(): FileNode[] { return this.dataChange.value; }

constructor() {
this.initialize();
}

initialize() {
// Parse the string to json object.
const dataObject = JSON.parse(TREE_DATA);

// Build the tree nodes from Json object. The result is a list of `FileNode` with nested
// file node as children.
const data = this.buildFileTree(dataObject, 0);

// Notify the change.
this.dataChange.next(data);
}

/**
* Build the file structure tree. The `value` is the Json object, or a sub-tree of a Json object.
* The return value is the list of `FileNode`.
*/
buildFileTree(obj: {[key: string]: any}, level: number): FileNode[] {
return Object.keys(obj).reduce<FileNode[]>((accumulator, key) => {
const value = obj[key];
const node = new FileNode();
node.filename = key;

if (value != null) {
if (typeof value === 'object') {
node.addchildren(this.buildFileTree(value, level + 1));
} else {
node.type = value;
}
}

return accumulator.concat(node);
}, []);
}
addPictureFile():void {
var picNode = this.data.find((node) => node.filename == 'Pictures');
var newNode = new FileNode();
newNode.filename = 'foo';
newNode.type = 'gif';
picNode.addChild(newNode);
}
}

/**
* @title Tree with nested nodes
*/
@Component({
selector: 'tree-nested-overview-example',
templateUrl: 'tree-nested-overview-example.html',
styleUrls: ['tree-nested-overview-example.css'],
providers: [FileDatabase]
})
export class TreeNestedOverviewExample {
nestedTreeControl: NestedTreeControl<FileNode>;
nestedDataSource: MatTreeNestedDataSource<FileNode>;

constructor(private database: FileDatabase) {
this.nestedTreeControl = new NestedTreeControl<FileNode>(this._getChildren);
this.nestedDataSource = new MatTreeNestedDataSource();

database.dataChange.subscribe(data => {
this.nestedDataSource.data = data;
}
);
}

hasNestedChild = (_: number, nodeData: FileNode) => !nodeData.type;

private _getChildren = (node: FileNode) => node.children;
}

关于Angular Material Tree 不显示填充数组的子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53919593/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com