I have created a custom component in Angular that projects content provided:
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-box',
template: '<ng-content select="[body]"></ng-content>',
})
export class BoxComponent {
constructor() {}
}
I use it like this in application.component.html:
<app-box>
<div body>1</div>
</app-box>
Causing digit 1 to be displayed.
Now, I would like to pass variable number of items to the app-box component in the template, and display them selectively in the app-box component.
Something like this:
app-box component:
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-box',
template: '<ng-content select="[body]:nth-of-type(2)"></ng-content>', /* :nth-of-type(2) */
})
export class BoxComponent {
constructor() {}
}
app.component.ts:
<app-box>
<div body>1</div>
<div body><b>2</b></div>
<div body><i>3</i></div>
</app-box>
The code presented should show the second div (digit 2).
How to show specific div by its number?
CodePudding user response:
Not really sure i understand you'r problem but i will try.
You want to add more than 1 element in ng-content
right ?
You can specify some content in ng-content
Default:
<ng-content></ng-content>
Question:
<ng-content select="[question]"></ng-content>
And use it like that :
<my-component>
<p Question>
How are you ?
</p>
<p>
Im Default
</p>
</my-component>
not native speaker :) hope you understand me
CodePudding user response:
Since you're working with multiple, variable number of items, I'd do something like the following:
<div *ngFor="let item of items; let i = index">
<app-box itemToShow="i">
<div >1</div>
<div >2</div>
<div >3</div>
</app-box>
</div>
Then, in your app-box
component, you can bind the selector to the itemToShow
input.
<ng-content select=".{{itemToShow}}"></ng-content>