We are currently working on an Angular2 application.
I recently developed a versatile component for handling a group of checkboxes.
Since the component is supposed to be generic and handle any set of objects belonging to the same TypeScript class, I decided to implement a model adapter approach inspired by Wicket. Though not exactly similar, as I am passing individual callbacks:
<wu-checkboxes [groupName]="'includedApps'"
[options]="availableApps"
[valueCallback]="appsValueCallback"
[labelCallback]="appsLabelCallback"
[equalsCallback]="equalsCallback"
[(checkedOptions)]="applicationGroup.applications"
(checkedOptionsChange)="onCheckedOptionsChange()"
>
</wu-checkboxes>
The callback functions are defined as follows:
appsValueCallback = (app: RegisteredApplication) => ""+app.id;
appsLabelCallback = (app: RegisteredApplication) => app.title;
equalsCallback = (a1: RegisteredApplication, a2: RegisteredApplication) => a1.id === a2.id;
availableApps: RegisteredApplication[];
includedApps: RegisteredApplication[];
In the actual component, we have this code snippet:
<div *ngFor="let option of _options">
<label>
<input type="checkbox" [name]="groupName"
[value]="valueCallback(option)"
[checked]="shouldBeChecked(option)"
(change)="handleCheckboxChange(option, $event)"
/>
{{labelCallback(option)}}
</label>
</div>
Also, there is this method:
shouldBeChecked(option: ItemType): boolean {
console.log("shouldBeChecked() called.", option, this.checkedOptions);
return ...
}
I anticipated that shouldBeChecked would only be executed once per checkbox.
However, after checking the console, shouldBeChecked()
seems to be invoked multiple times, even if there's just one checkbox during the initial rendering. I confirmed that ngAfterViewChecked
and ngAfterViewChanged
are triggered only once for the checkboxes component.
TLDR:
- Why is Angular2 calling shouldBeChecked so frequently?
- Does this suggest a mistake in the setup of the component, page, or application?
- How can I determine the root cause of these repeated calls? The stack traces don't offer much insight to me.