Home > front end >  array change detection property in Angular
array change detection property in Angular

Time:01-01

I have an component in which i am showing values fetched from database. there is also Add button. on click of Add , i am pushing text field value to array. same is binded to component. The value is getting set in array. [(ngModel)] but not displaying in text box. only displaying when i click inside box. i not able to identify cause for this behaviour. plz help

onAdd() {
  if (this.emailRecipients.length === 0) {
    this.emailRecipients = [];
  }
  this.emailRecipients.push(this.enterEmailAddress);
         
}   


</div>

CodePudding user response:

This is because of Angular Change Detection, and is an expected behavior.

Instead of modifying the array by calling .push, you should be creating a new array instance for the changes to be reflected.

    this.emailRecipients = [...this.emailRecipients, this.enterEmailAddress];

From PrimeNG docs:

Change Detection of Suggestions AutoComplete uses setter based checking to realize if the suggestions has changed to update the UI. In order this to work, your changes such as adding or removing a record should always create a new array reference instead of manipulating an existing array as Angular does not trigger setters if the reference does not change.

Note that if no suggestions are available after searching, provide an empty array instead of a null value.

Reference: AutoComplete

CodePudding user response:

write it like this,

onAdd() {
  if (this.emailRecipients.length === 0) {
    this.emailRecipients = [];
  }
  this.emailRecipients.push(this.enterEmailAddress);
  this.emailRecipients = [...this.emailRecipients];
         
}
  • Related