0

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?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Yea @Marek, it works! Thanks, Actually what does this ChangeDetectorRef do? Kudos!
Calls manually changeDetection, it's not topic for couple of words, you can read more for example here medium.com/ngconf/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.