Angular 变量未刷新(未在模板中正确显示)

Angular variable is not refreshing (not displayed correctly in template)

有 2 个组件:graphnode 和 1 项服务:nodesmanager

nodesmanager被注入graph

graph组件检测到鼠标点击事件时,注入的服务nodesmanager通过调用函数AddNode创建一个新节点n,调用n.setPos (22,44),并将 n 添加到节点列表 nodes.

setPos 应该更改 node 的 2 个变量:posXposY

然后模板 node.html 应该“回显” posX : {{posX}}

但问题是{{posX}}没有显示在setPos之后改变的posX的值,它没有显示任何东西。它正在考虑 posX 未定义。

nodesmanager.service.ts:

@Input() nodes: NodeComponent [] = [] ;
constructor() { }
  
AddNode (x: number, y: number): void {
    let n = new NodeComponent ();
    n.SetPos(22,44);
    this.nodes.push (n);
}

node.ts:

@Input()  posX: number;
@Input()  posY: number;

constructor(){}

SetPos (_posX: number, _posY: number): void{
    this.posX = _posX;
    this.posY = _posY;
    
}

ngOnInit() {}

node.html (template):

<div>
    p: {{posX}}
</div>

graph.ts:

constructor(public nodesManager: NodesManagerService) { }
ngOnInit() {}
  
MouseClicked (event: MouseEvent) : void {
    this.nodesManager.AddNode(event.clientX, event.clientY);
}

graph.html (template):

<div class="graph" (click) = "MouseClicked($event)">
    <div *ngIf="nodesManager.nodes">
        <div *ngFor = "let node of nodesManager.nodes">
            <app-node></app-node>
        </div>
    </div>
</div>

从 NodeComponent 中删除 SetPos class

将节点管理器服务更改为只保存数据

public nodes: any[] = [] ;
constructor() { }
  
AddNode (x: number, y: number): void {
    this.nodes.push ({x, y});
}

更改模板

<div class="graph" (click)="MouseClicked($event)">
    <div *ngIf="nodesManager.nodes">
        <div *ngFor="let node of nodesManager.nodes">
            <app-node [posX]="node.x" [posy]="node.y"></app-node>
        </div>
    </div>
</div>