Angular 2 bind input to function call

Is it permissible to bind the @Input() property of a child component to a function call of the parent component, for example:

 <navigation [hasNextCategory]="hasNextCategory()" [hasPreviousCategory]="hasPreviousCategory()" (nextClicked)="nextCategory()" (previousClicked)="previousCategory()" (submitClicked)="submit()" </navigation> 

It seems to work, but I wonder how. Are these inputs reevaluated when an event is fired from a component, or what leads to input binding?

+5
source share
1 answer

Sure. The function is called every time a time change check is performed, and assigns the result of the function call to the input property.

You get an exception in devMode when 2 consecutive calls return different values. as

 hasNextValue() { return {}; } 

Exception: expression has changed ...

It is not recommended to associate with functions. Rather, assign the result to the property and bind it to this property. If you know that you are doing it well, though.

Update

so return true / false according to some internal state is not allowed? Strange that my navigation is still working

It is allowed. If your state changes due to some event (click, timeout, ...), then Angular will change the expected detection changes. If Angular change detection calls a method twice (as in devMode) without any event between them, then it does not expect changes and throws the exception mentioned above. What Angular dislikes is when change detection causes change.

The following is an example of an exception, since the detection of changes itself will change the state of the components ( this.someState = !this.someState; ) which is not allowed.

 someState:boolean = false; hasNextValue() { this.someState = !this.someState; return this.someState; } 

Two consecutive calls return false and true , even if no event has occurred between them.

This example will work fine though

 someState:boolean = false; @HostListener('click') { this.someState = !this.someState; } hasNextValue() { return this.someState; } 

because two consecutive calls (without any event between them) return the same value.

+9
source

All Articles