Angular project options into child component

Viewed 41

I'd like to project select options into a child component with ng-content like this:

<custom-select>
  <option *ngFor="let name of names" [ngValue]="name">{{ name.name }}</option>
</custom-select>

In the child component, I use a compare function, called by [compareWith] and ng-content.

<select matNativeControl [(ngModel)]="selectedValue" [compareWith]="compareB">
  <ng-content></ng-content>
</select>

If I inject the options with ng-content from the parent component, the compareWith function is not triggered. If I do the same with options inside the child component, it works.

I have a Stackblitz example here: https://stackblitz.com/edit/angular-ymoj4d?file=src/app/app.component.html

What do I miss?

1 Answers

In your custom-select.component.ts add select attribute to ng-content

<select matNativeControl [(ngModel)]="selectedValue" [compareWith]="compareB">
  <ng-content select="[options]"></ng-content>
</select>
{{ selectedValue.name }}

and then in your app.component.ts add defined selector of content projection to option:

<custom-select>
  <option options *ngFor="let name of names" [ngValue]="name">{{ name.name }}</option>
</custom-select>
Related