I'm creating a component. Since I like the Apache Wicket way of doing things, I am trying to emulate the IModel
way of passing data. For that, to the child component I pass a model and callbacks which can pull out the relevant values, instead of calling a function to get the data upfront.
The problem is, that handling of the newly set model uses the callbacks.
So if the model setter is called before callbacks are set, Angular crashes.
Workaround: postpone the actions that need the callback to ngAfterViewInit()
or such.
In short:
Example: (Changing the order here seems to do the job)
@Input()
valueCallback: (item: any) => string
= app => { throw new Error("valueCallback not yet defined."); };
@Input()
labelCallback: (item: ItemType) => string;
Template using that child component: (changing the order here doesn't change the order)
<wu-checkboxes [groupName]="'includedApps'"
[options]="availableApps"
[valueCallback]="appsValueCallback"
[labelCallback]="appsLabelCallback"
>
As I mention above, Angular2 seems to follow the order of the @Input
class members and sets/calls them in that order. The question is, is that de-facto or de-jure? I don't want to rely on features that work just because it's currently coded that way. I don't know much about JavaScript reflection, so I can't tell whether this is going to work everywhere.
If you click on the “set to Parent” button multiple times, the child component setter won't be triggered from 2nd time onward. Thus it looks like the Input setter is only being fired once if the value of the setter hasn't been changed.
@Input Decorator. @Input is a decorator to mark a property as an input. @Input is used to define an input property, to achieve component property binding. @Inoput decorator is used to pass data (property binding) from parent to child component.
The @Input() decorator in a child component or directive signifies that the property can receive its value from its parent component.
You can use ngOnChanges()
which is called every time an @Input()
is updated by change detection. You can check within ngOnChanges
whether all input values are already available and then execute your code.
You need to take care yourself though, that subsequent updates don't trigger the function call again (in case this is not desired).
update
The order of bindings (value bindings and event bindings) is undefined in Angular2 and therefore you can't rely on a specific order.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With