How to work with asynchronous inputs in components?

I have a problem with ngOnChange . I have the following component:

 @Component({ selector:'user-table', template: `...`, }) export class UserTable implements OnChanges{ @Input() users: User[]; years:string[]; constructor(private _usersCollection:UsersCollection){ } ngOnChanges(){ if (this.users.length) {this.years =this._usersCollection.createYearsArray(this.users)} } } 

However, if the condition is checked only once - when this.users has not yet been received from the server, and therefore its length is 0. How can I find a solution to work with such asynchronous inputs?

The array is updated when I install the following logs:

  console.log('ON FIRST INIT' , this.programs); this.years = this._usersCollection.createYearsArray(); console.log(this.years); setInterval(()=>{ console.log('IN INTERVVAL' , this.programs); },1000); 

Console output:

 ON FIRST INIT [] UsersTable.component.ts:21 [] UsersTable.component.ts:23 IN INTERVVAL [Object, Object, Object, Object] 
+8
angular
source share
2 answers

If you do not need to execute any logic when changing your input property (for example, you use only the property in relation to the template), you do not need to do anything. Angular will automatically propagate new values ​​from parent to input property.

If you want to execute some component logic when changing an input property, use ngOnChanges() , which is called whenever any input property changes.

Since Angular uses === to detect changes (well, there is some special processing for NaN ), this means that

  • for reference types (Array, Object, Date, etc.), the reference (i.e. the reference to an array, object, etc.) should change. For example, myArray = someNewArray;
    If only the element in the array changes, ngOnChanges() not called. For example, for a change such as myArray[0].name = newName; , ngOnChanges() not called.
  • for primitive types (number, boolean, string), this simply means that the value must change. For example, myNumber = 5; or myNumber = newNumber ;

Another option is to implement your own change detection logic using ngDoCheck() . See this answer for an example. This lifecycle hook is called "every time the input properties of a component or directive are checked. Use it to extend the detection of changes by performing a custom check" - from lifecyle hooks.md

+7
source share

ngOnChanges() is called when users updated. You just need to make sure that the new array is assigned to users in the parent component instead of populating the existing array. Otherwise, the detection of angle changes does not recognize the changes.

0
source share

All Articles