我正在构建一个仪表板来管理公司内部的用户。那家公司有不同数量的部门和这些部门内部的一堆子弟,所以我有一个自定义的递归树视图来显示它们之间的关联。
现在,当我单击树的某个分支时,我需要从树中向父组件发送一个标识该部门/子公司 ( cd ) 的数字,其中显示了相关工作人员和有关他们的数据。在父组件中,该编号用于从数据库中获取与该部门/子女相关的所有数据。
为此,我在论坛中读到我可以使用@Input / @Output装饰器和EventEmitter。它有效,但只有一次。当我单击另一个分支时,接收cd的方法(称为receiveNode())不会更新,并且仅适用于第一个分支。这不是所需的行为。
为了测试,在发出 CD 变量的相同方法中,我将分支的 CD 登录到控制台。我可以看到每次单击分支时都可以记录 CD 变量,但只能通过 Event Emitter 发送一次
tree.component.ts (子)
import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { Input } from '@angular/core';
import { TreeNode } from '../../interfaces/tree-node';
@Component({
selector: 'app-tree',
templateUrl: './tree.component.html',
styleUrls: ['./tree.component.css']
})
export class TreeComponent implements OnInit {
@Input() treeData: TreeNode[];
// Enviar CD do organigrama para o BuildOrganigComponent
@Output() eventEmitter: EventEmitter<number> = new EventEmitter();
nome: string;
constructor() { }
ngOnInit() { }
toggleChild(node) { node.showChildren = !node.showChildren; }
sendNode(cd) {
console.log(cd);
this.eventEmitter.emit(cd);
}
}
树.component.html
<ul *ngIf="treeData">
<li *ngFor="let node of treeData">
<span *ngIf="node.children != 0">
<i (click)="toggleChild(node)" id="seta-direita" class="fas fa-angle-right fa-fw"></i>
</span>
<span id="row" (click)="sendNode(node.cd)">{{ node.nome }}</span>
<app-tree *ngIf="!node.showChildren" [treeData]="node.children"></app-tree>
</li>
</ul>
函数组件.ts
receiveNode(e) {
console.log(e);
}
函数.component.html
<div class="overflow" style="margin-left: -5% !important;">
<app-tree [treeData]='nodes' (eventEmitter)='receiveNode($event)'></app-tree>
</div>
funcion.html 和 funcion.ts 很大,所以只放重要的东西。如果需要查看整个代码,请告诉我。
在第二张图片中,我们可以看到来自树组件和功能组件的日志,但是之后,无论我单击哪里,它都不会调用功能组件中的方法。
可能有什么问题?任何帮助表示赞赏