Ibanez1408
Ibanez1408

Reputation: 5058

Angular 2 view is not updating when variable is changed in ts

Can you please tell me why my value in the html does not change when my variable gets updated? This is my code in the ts

private peer: any;
private anotherId: 'opopo'
public myPeerId: '123456';
ngOnInit(): void {
    this.peer = new Peer();

    this.peer.on('open', function (connectionId) {
      this.myPeerId = connectionId;
      console.log(this.myPeerId)
    });
  }

I can log my variable value when it changes but somehow, my html does not. Please see my html code

<h1>My id - {{myPeerId}}</h1>
<input type="text" [(ngModel)]="anotherId" >
<button (click)="connect()">Connect</button>

Thank you.

Upvotes: 0

Views: 27

Answers (1)

Barremian
Barremian

Reputation: 31125

If you look at the console, you will see an error similar to

Cannot read property 'myPeerId' of undefined

To refer to the class scope using this keyword in callbacks, use arrow function notation

this.peer.on('open', (connectionId) => {     // <-- arrow notation here
  this.myPeerId = connectionId;
  console.log(this.myPeerId)
});

Upvotes: 1

Related Questions