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

Viewed 312

There are 2 components : graph, node And 1 service: nodesmanager

nodesmanager is injected in graph

When the graph component detects a mouse click event, the injected service nodesmanager create a new node n by calling a function AddNode, call n.setPos (22,44), and add n to a list of nodes nodes.

setPos should change 2 variables of node: posX and posY.

Then the template node.html should "echo" posX : {{posX}}

But the problem is {{posX}} is not displaying the value of posX changed after setPos, It is not showing anything. It is considering posX to be undefined.

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>
1 Answers

Remove SetPos from the NodeComponent class

Change the nodesmanager service to just hold data

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

Change your template

<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>
Related