Вы можете выбрать один из следующих методов:
Если он доступен только для 2 компонентов, вы можете получить к ним доступ с помощью методов получения QueryList (первый и последний)
@ContentChildren(TemplateRef) templates: QueryList<TemplateRef<any>>;
ngAfterContentInit() {
console.log(this.templates.first); // Gives you the 1st template child
console.log(this.templates.last); // Last template child (2nd child)
}
Поиск по индексу
this.templates.find((template, index) => index == 1); // 2nd template child
Другая альтернатива
Создал Stackblitz Демо , используярасширение для Компонентов
1.) Создайте TemplateContentComponent Это послужит вашим ChildComponent и добавит @Input ()
@Component({
selector: 'template-content',
template: `
// If no ng-template reference available, show its ng-content
<ng-content *ngIf="!template"></ng-content>
// Else, show the ng-template through ng-container
<ng-container *ngIf="template"
[ngTemplateOutlet]="template"></ng-container>
`
})
export class TemplateContentComponent {
@Input() name: string; // Serves as your component id
}
2.) Создать TemplateContainerComponent - это будет служить ParentComponent
@Component({
selector: 'template-container',
template: `<ng-content></ng-content>`
})
export class TemplateContainerComponent implements AfterContentInit {
@ContentChildren(TemplateContentComponent) templates: QueryList<TemplateRef<any>>;
ngAfterContentInit() {
// You can now check whether you'll be fetching a template
// based on the names you want provided from parent template.
const t1 = this.templates.find((template: any) => template.name === 't1');
console.log(t1); // This will show the t1 component
// which t1 and t2 are the same component
// but had set a name @Input() as their ID
}
}
![Result](https://i.stack.imgur.com/ZnjjY.png)
3.) Вкл.Ваш AppComponent Шаблон
<template-container>
// Can be a raw template, good for ng-content
<template-content [name]="'t1'">t1 template</template-content>
// Or a template from ng-template, good for ng-container
<template-content [name]="'t2'"
[template]="userList"></template-content>
</template-container>
// User List Template
<ng-template #userList>
<h1>User List</h1>
</ng-template>
![Template](https://i.stack.imgur.com/D6V0g.png)