Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Change Angular Label Dynamically with Received Value

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    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?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading