How to get reference of Component from projected content

I am writing a common angular library component, where the consumers can pass on optional content/template/component through angular content projection mechanism. Below are some example classes to explain better.

The hierarchy tree:

consuming-component – projects component-to-project —–>

common-container – forwards projected content to it’s child ——>

common-item – projected content renders here.

Common Library:

component-to-project.component.ts – this is the component that will finally render inside common-item and is projected from the consuming component.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>@Component({
selector: 'component-to-project',
template: '<p>Projected Successfully!</p>',
})
export class ComponentToProjectComponent {}
</code>
<code>@Component({ selector: 'component-to-project', template: '<p>Projected Successfully!</p>', }) export class ComponentToProjectComponent { … } </code>
@Component({
  selector: 'component-to-project',
  template: '<p>Projected Successfully!</p>',
})
export class ComponentToProjectComponent { … }

common-container.component.ts – This is the intermediate component that passes on the projected content to common-item.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>@Component({
selector: 'common-container',
templateUrl: './common-container.component.html',
styleUrls: ['./common-container.component.scss'],
})
export class CommonContainerComponent {
@ContentChild(TemplateRef) projectedTemplateRef!: TemplateRef<any>;
()
}
</code>
<code>@Component({ selector: 'common-container', templateUrl: './common-container.component.html', styleUrls: ['./common-container.component.scss'], }) export class CommonContainerComponent { @ContentChild(TemplateRef) projectedTemplateRef!: TemplateRef<any>; (…) } </code>
@Component({
  selector: 'common-container',
  templateUrl: './common-container.component.html',
  styleUrls: ['./common-container.component.scss'],
})
export class CommonContainerComponent {
    @ContentChild(TemplateRef) projectedTemplateRef!: TemplateRef<any>;
(…)
}

common-container.component.html

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>...
<div>
<common-item>
<ng-template let-context>
<ng-container [ngTemplateOutlet]="projectedTemplateRef" [ngTemplateOutletContext]="{$implicit: context}">
</ng-container>
</ng-template>
</common-item>
</div>
()
</code>
<code>... <div> <common-item> <ng-template let-context> <ng-container [ngTemplateOutlet]="projectedTemplateRef" [ngTemplateOutletContext]="{$implicit: context}"> </ng-container> </ng-template> </common-item> </div> (…) </code>
...

<div>
    <common-item>
        <ng-template let-context>
            <ng-container [ngTemplateOutlet]="projectedTemplateRef" [ngTemplateOutletContext]="{$implicit: context}">
            </ng-container>
        </ng-template>
    </common-item>
</div>
(…)

common-item.component.ts – This is where the projected content actually renders.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>@Component({
selector: 'common-item',
templateUrl: './common-item.component.html',
styleUrls: ['./common-item.component.scss'],
})
export class CommonItemComponent {
@ContentChild(TemplateRef) projectedTemplateRef!: TemplateRef<any>;
templateContext: MyContextData = {};
ngAfterContentInit() {
// This is where I need the reference to the component passed through content projection.
projectedComponent: ComponentToProject = // get component
}
()
}
</code>
<code>@Component({ selector: 'common-item', templateUrl: './common-item.component.html', styleUrls: ['./common-item.component.scss'], }) export class CommonItemComponent { @ContentChild(TemplateRef) projectedTemplateRef!: TemplateRef<any>; templateContext: MyContextData = { … }; ngAfterContentInit() { // This is where I need the reference to the component passed through content projection. projectedComponent: ComponentToProject = // get component } (…) } </code>
@Component({
  selector: 'common-item',
  templateUrl: './common-item.component.html',
  styleUrls: ['./common-item.component.scss'],
})
export class CommonItemComponent {
    @ContentChild(TemplateRef) projectedTemplateRef!: TemplateRef<any>;
    
    templateContext: MyContextData = { … };

    ngAfterContentInit() {
        // This is where I need the reference to the component passed through content projection.
        projectedComponent: ComponentToProject = // get component
    }
    (…)
}

common-item.component.html

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>()
<div>
<ng-container [ngTemplateOutlet]="projectedTemplateRef" [ngTemplateOutletContext]="{$implicit: templateContext}">
</ng-container>
</div>
()
</code>
<code>(…) <div> <ng-container [ngTemplateOutlet]="projectedTemplateRef" [ngTemplateOutletContext]="{$implicit: templateContext}"> </ng-container> </div> (…) </code>
(…)
<div>
    <ng-container [ngTemplateOutlet]="projectedTemplateRef" [ngTemplateOutletContext]="{$implicit: templateContext}">
    </ng-container>
</div>
(…)

Consuming Application (Common Library is added as dependency)

consuming-app.component.html

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>()
<common-container>
<ng-template let-context>
<component-to-project (data)="context.data"></component-to-project>
</ng-template>
</common-container>
()
</code>
<code>(…) <common-container> <ng-template let-context> <component-to-project (data)="context.data"></component-to-project> </ng-template> </common-container> (…) </code>
(…)
<common-container>
    <ng-template let-context>
        <component-to-project (data)="context.data"></component-to-project>
    </ng-template>
</common-container>
(…)

I want the reference to the component-to-project component inside common-item component if this is what is being projected from consuming app.

I have tried few different approaches to get the projected component reference in the common-child component but got undefined in all cases.

  • Added a reference (<component-to-project #myComponent>) to the projected component and resolve it using @ContentChild in common-item component

    Plain text
    Copy to clipboard
    Open code in new window
    EnlighterJS 3 Syntax Highlighter
    <code> @ContentChild('myComponent', { descendants: true })
    projectedComponent?: ComponentToProjectComponent;
    </code>
    <code> @ContentChild('myComponent', { descendants: true }) projectedComponent?: ComponentToProjectComponent; </code>
      @ContentChild('myComponent', { descendants: true }) 
       projectedComponent?: ComponentToProjectComponent;
    
  • Resolve it using component class as selector of @ContentChild in common-item component

    Plain text
    Copy to clipboard
    Open code in new window
    EnlighterJS 3 Syntax Highlighter
    <code> @ContentChild(ComponentToProjectComponent, { descendants: true })
    projectedComponent?: ComponentToProjectComponent;
    </code>
    <code> @ContentChild(ComponentToProjectComponent, { descendants: true }) projectedComponent?: ComponentToProjectComponent; </code>
      @ContentChild(ComponentToProjectComponent, { descendants: true })
       projectedComponent?: ComponentToProjectComponent;
    
  • Define an injection token for the component and use that injection token in @ContentChild to resolve.

    • component to project declaration module providers array
    Plain text
    Copy to clipboard
    Open code in new window
    EnlighterJS 3 Syntax Highlighter
    <code> { provide: TokenClass, useExisting: forwardRef(
    () => ComponentToProjectComponent).
    </code>
    <code> { provide: TokenClass, useExisting: forwardRef( () => ComponentToProjectComponent). </code>
      { provide: TokenClass, useExisting: forwardRef(
        () => ComponentToProjectComponent).
    
    • common-child
    Plain text
    Copy to clipboard
    Open code in new window
    EnlighterJS 3 Syntax Highlighter
    <code> @ContentChild(TokenClass) projectedComponent?:
    ComponentToProjectComponent;
    </code>
    <code> @ContentChild(TokenClass) projectedComponent?: ComponentToProjectComponent; </code>
      @ContentChild(TokenClass) projectedComponent?: 
      ComponentToProjectComponent;
    

However, none of the above approach worked.

New contributor

codestack is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật