Home > Software engineering >  Change Angular Label Dynamically with Received Value
Change Angular Label Dynamically with Received Value

Time:08-10

I am working on Angular - Node websockets, scenario is when the button is clicked, it will be sending a request to server and get data and update the received data on client-side. but it is not changing as per. code is below.

Label on component HTML

<h2>{{iSpeed}}</h2>

component.ts

    iSpeed: any;
    
    //BUTTONCLICK
    speedTest(){
        //WORKS
        this.iSpeed = "LOADING";
        socket.emit("checkedTrue");
    }
    ngOnInit(): void {
        socket.on('acknowledged', (data: any) =>{
            //LABEL CHANGE
            this.iSpeed = data.internetSpeed;
            alert(this.intSpeed = data.internetSpeed);
        })
    }

Angular Newbie, where I am being dumb?

CodePudding user response:

Looks like problem with change detection. You can try this

constructor(private cdr: ChangeDetectorRef) {}

ngOnInit(): void {
    socket.on('acknowledged', (data: any) =>{
        //LABEL CHANGE
        this.iSpeed = data.internetSpeed;
        
        this.cdr.detectChanges();
        alert(this.intSpeed = data.internetSpeed);
    })
}

If you are using onPush change detection strategy, first case works because change detection is called after click, but second one doesn't

  • Related