Angular 7: How to update the html variable automatically when its value is changed in the . ts file?

Asked

Viewed 874 times

0

I have a variable that gets value when the page renders, and it looks right in the template. However if I change its value with the page already loaded the value in . ts is updating (checked with console.log) but in html remains unchanged.

I’ve tried using ngModel but it didn’t work because I’m also using an array of objects and objects from that array.

html

<div *ngFor="let item of itens">            
     <textarea class="textarea" id="item-textarea" [value]="item.text"> 
     </textarea>
</div>

Ts

public itens:any[] = [];

constructor() {

}

ngOnInit() {
    this.initItens();
    this.changeItens();
}

initItens() {
    let item = new Item();
    item.text = "Hello world";
    this.itens.push(item);
}

changeItens() {
    let item = new Item();
    item.text = "Bye bye World";
    this.itens.push(item);
    console.log(this.itens); //saída conforme o esperado
}       

I wonder what needs to be done to be able to always update the variable in the file . ts also update in html, to angular 7.

Thank you.

  • Try it this way: this.items=[...this.items,item];

1 answer

1


Try to change the reference of your pro angular array to know that something has changed.

 this.itens=[...this.itens,item]
  • helped, thank you

Browser other questions tagged

You are not signed in. Login or sign up in order to post.