I have a tw-menu component which displays some content with content projection through an ng-content element.
<tw-button [data]="data?.Button||{}"></tw-button>
<div class="relative">
<div [class]="'absolute top'+top+' left'+left+' w'+menuWidth+ ' bg-transparent' " [hidden]="hideMenu">
<div [class]="'p-2 justify-center w'+menuWidth+' rounded-xl gap-2 flex flex-wrap bg-white'">
<ng-content></ng-content>
</div>
</div>
</div>
I've also implemented a hostlistener to register click events on tw-menu component. After a click event I display in the console the tw-button elements that are part of the ng-content
@Component({
selector: 'tw-menu',
standalone: true,
imports: [CommonModule,TwButtonComponent],
templateUrl: './tw-menu.component.html',
styleUrls: ['./tw-menu.component.scss']
})
export class TwMenuComponent implements OnInit {
@Input() data?:TwMenuData
hideMenu=true
menuVisibility(){
this.hideMenu=!this.hideMenu
}
@ContentChildren(TwButtonComponent) query!:QueryList<TwButtonComponent>
@HostListener('click', ['$event.target'])
onClick() {
console.log (this.query.map(x=>x))
this.menuVisibility()
}
Now, I have the following template which showcases the problem, which includes two tw-menu elements. The first one passes its content directly with a tw-button component. The second passes the same element, but not directly, but through an ng-template element.
<div class="flex">
<tw-menu [data]="{Button:{Text:'Menu normal'}}">
<tw-button [data]="{Text:'Option 1'}">
</tw-button>
</tw-menu>
<tw-menu [data]="{Button:{Text:'Menu ng-template'}}">
<ng-container *ngTemplateOutlet="content"></ng-container>
</tw-menu>
</div>
<ng-template #content>
<tw-button [data]="{Text:'Option 1'}">
</tw-button>
</ng-template>
When I click the first tw-menu, the console displays the tw-button component. But when I click the second menu, all I get is an empty array.
I imagine that the problem is that ContentChildren registers children before the ng-template is applied on the template
Is there a solution to this, so I can be able to use the ng-template as data for the ng-content?
.