Может быть этот доклад будет полезен.
Насколько я понимаю, ng-content
не создает контент, он просто перемещает контент из одной части в другое.
Я думаю, что решение вашей проблемы - использовать ng-template
. Например:
projected.component.ts
let instances = 0;
@Component({
selector: 'app-projected',
template: `projected instance nr: {{ instanceId }}`
})
export class ProjectedComponent implements OnInit {
instanceId: number;
constructor() { }
ngOnInit() {
this.instanceId = ++instances;
}
}
parent.component.ts
@Component({
selector: 'app-parent',
template: `
<h3>Parent component</h3>
<p>Using content #1</p>
<ng-container *ngTemplateOutlet="content"></ng-container>
<p>Using content #2</p>
<ng-container *ngTemplateOutlet="content"></ng-container>
`,
})
export class ParentComponent implements OnInit {
@ContentChild('content', { read: TemplateRef }) content: TemplateRef<any>;
constructor() { }
ngOnInit() {
}
}
И вот что важно:
<app-parent>
<ng-template #content>
<app-projected></app-projected>
</ng-template>
</app-parent>
Насколько я понимаю, то, что внутри ng-template
, можно рассматривать как проект. Поэтому каждый раз, когда вы используете ng-template
, вы создаете новый экземпляр этого чертежа.
Demo