3

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?

Claies
  • 22,124
  • 4
  • 53
  • 77
John Ryan
  • 230
  • 2
  • 11
  • 1
    Can you give an example of why a user would want to use a custom day? – Sam Orozco Sep 26 '18 at 18:59
  • 1
    A custom day element is just so that users of the API can display dates however they like (colors, custom indicators, etc) for a given day, without worrying about what days need to be rendered at any given time. for example, if the user selects a different month (e.g. Oct) the user may decide that they want to display an icon indicating there is an event on October 1st – John Ryan Sep 26 '18 at 19:04

1 Answers1

2

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.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567