Issue
I am building a calendar component, and I would like to provide the following API to users:
<fancy-calendar>
<my-custom-day [day]="day"></my-custom-day>
</fancy-calendar>
Where fancy-calendar
is responsible for keeping track of the current month that the user selects. Internally, I would like to implement it using something like *ngFor:
<div *ngFor="let day of daysInMonth">
<ng-content [day]="day"></ng-content>
</div>
This doesn’t seem to work because ng-content
can’t send arbitrary values (in this case, the current day.)
Do I need to write a custom directive for this? How can I give users the ability to use their own component for days?
Solution
You can do this by using dynamic component loading.
https://github.com/dart-lang/angular/blob/7f6858bc48c1d2a454a4bc350077d67c277c6516/doc/faq/component-loading.md
I answered a similar question for TS in Angular dynamic tabs with user-click chosen components
The easiest way to use this with *ngFor
is to build a helper component that you pass the type or factory to for the component you want it to create.
Another way would be using https://webdev.dartlang.org/api/angular/angular/NgTemplateOutlet-class
where the user passes content as template
<fancy-calendar>
<ng-template>
<my-custom-day [day]="day"></my-custom-day>
</ng-template>
</fancy-calendar>
and fancy-calender
uses NgTemplateOutlet
to render it.
With *ngFor
https://webdev.dartlang.org/api/angular/angular/NgFor/ngForTemplate could be used as well to render the same template multiple times.
Answered By – Günter Zöchbauer
Answer Checked By – Dawn Plyler (FlutterFixes Volunteer)