Angular2: How to configure @ Input setters in a specific order?

I am creating a component. Since I like the way Apache Wicket does things, I'm trying to emulate the way IModel data. To do this, I pass the model and callbacks to the child component, which can pull the appropriate values, instead of calling the function to get the data in advance.

The problem is that processing the newly defined model uses callbacks. Therefore, if the caller of the model is called before the callbacks are set, Angular fails.
Workaround: Delay actions requiring a callback to ngAfterViewInit() or such.

In short:

  • How can I control the order in which @Inputs is installed?
  • Is it possible to rely on the order in the source code?

Example: (Reordering 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 this child component: (reordering here does not reorder)

  <wu-checkboxes [groupName]="'includedApps'" [options]="availableApps" [valueCallback]="appsValueCallback" [labelCallback]="appsLabelCallback" > 

As I mentioned above, Angular2 seems to follow the order of the members of the @Input class and sets / calls them in that order. The question is, de facto or de jure? I do not want to rely on functions that work just because they are currently encoded in this way. I don't know much about JavaScript reflection, so I can't say if this will work everywhere.

+5
source share
1 answer

You can use ngOnChanges() , which is called every time @Input() updated by detecting changes. You can check inside ngOnChanges if all input values ​​are available and then execute your code. You must make sure that subsequent updates no longer call the function (in case this is undesirable).

Update

The binding order (value binding and event binding) is undefined in Angular2, and therefore you cannot rely on a specific order.

+3
source

Source: https://habr.com/ru/post/1264484/


All Articles