Managing multiple `ng-content` slots in Angular can be a daunting task. Here

I am facing an issue with a component where I have declared an input as follows:

@Input() isOverlay: boolean

The template html for this component looks like this:

  
        <ng-template *ngIf="isOverlay" cdkConnectedOverlay [cdkConnectedOverlayOrigin]="trigger" [cdkConnectedOverlayOpen]="active">
          <div class="context-menu__header">
            <strong>{{ label }}</strong>
          </div>
          <ng-content></ng-content>
          <div class="context-menu__footer"></div>
        </ng-template>

        <ng-container *ngIf="!isOverlay">
          <div class="context-menu__header">
            <strong>{{ label }}</strong>
          </div>
          <ng-content></ng-content>
          <div class="context-menu__footer"></div>
        </ng-container>
    
  

Although it works, the presence of two ng-content tags seems to be causing an issue. When I pass the boolean value as true and comment out the second ng-content tag, it works fine. But if I leave both ng-content tags, it doesn't work. Any idea why?

Answer №1

After attempting to replicate the issue you mentioned, I realized it was quite challenging without sufficient details. I managed to come up with a solution: here is the stackblitz link

component.ts

export class HelloComponent {
  isOpen = false;
}

component.html

<button (click)="isOpen = !isOpen" cdkOverlayOrigin #trigger="cdkOverlayOrigin">
   show overlay with stuff
</button>
<hr/>
<ng-template
*ngIf="isOpen"
cdkConnectedOverlay
[cdkConnectedOverlayOrigin]="trigger"
[cdkConnectedOverlayOpen]="isOpen"
>
   from overlay: 
   <ng-container *ngTemplateOutlet="tpl"></ng-container>
</ng-template>
<div *ngIf="!isOpen">
   outside overlay: 
   <ng-container *ngTemplateOutlet="tpl"></ng-container>
</div>
<ng-template #tpl>
   <ng-content></ng-content>
   World!
</ng-template>

In a single component, only one projection of ng-content is allowed. By placing it within the ng-template, it can be shared across multiple sections. However, displaying it simultaneously in numerous places is not recommended.

If you wish to showcase it multiple times, nest it inside a separate template within the parent component and pass the ng-template through normal @Input binding. You may refer to this documentation for further clarification: Click here for more information

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to retrieve all mandatory attributes of a TypeScript object?

Is there a method or approach available that can retrieve all necessary properties from a TypeScript interface or an object? For instance, something along the lines of Object.getOwnPropertyDescriptors(myObject) or keyof T, but with the specific details o ...

Tips for saving the generated POST request ID for future use in another function

I am facing a challenge where I want to use the ID of a newly created Order as the OrderId for an OrderLine that needs to be created immediately after. After creating the Order, if I log the orderId INSIDE THE SUBSCRIBE METHOD, it shows the correct value. ...

What is the best choice for a package.json file in an ASP.NET MVC project: devDependencies or dependencies?

I am currently in the process of developing an ASP.NET Core 2.0 MVC application and incorporating Angular 4 into it. To manage my dependencies, I have set up a configuration file named package.json in the root directory. Instead of using angular-cli, I ha ...

An issue was encountered when attempting to log out the user from Firebase

My website is built using the Ionic and Angular Frameworks along with Firestore database. The signout feature works as expected, but unfortunately, an error occurs when a user tries to sign out of their account. The error message: FirebaseError: Missing o ...

Closing the side navigation bar when a router link is clicked on small devices

In my project, I have implemented the side-nav component for routing between different components. Here is how it looks: https://i.stack.imgur.com/v6hE8.png However, I am currently facing an issue with the side-nav. On mobile devices, the side-nav appear ...

Exploring Vue.js lifecycle events and when to begin loading store properties (Vue.observable)

Currently, I am utilizing Vue.observable() for state management and it is crucial for two store properties to be fully loaded before most views are rendered by vue-router. I have attempted implementing the loading logic in various lifecycle events such as ...

Filter error - Unable to retrieve property 'toLowerCase' from null value

When filtering the input against the cached query result, I convert both the user input value and database values to lowercase for comparison. result = this.cachedResults.filter(f => f.prj.toLowerCase().indexOf((this.sV).toLowerCase()) !== -1); This ...

How come this mocha test is exceeding its timeout limit when making a basic call with mongoose?

Trying to write a simple assertion for an asynchronous database method: describe('User Repository', () => { describe('findById', () => { it('Returns a user that can be found in the database by ID', async () => { ...

Invoke Observable.subscribe() sequentially

I have an array of objects and need to iterate over each element, making a request to the service for each one. However, I want to ensure that the next iteration only occurs when the current request is successfully completed, or block any further requests. ...

There is no index signature containing a parameter of type 'string' within the type '{ appointments: { label: string; id: number; minWidth: number; }[]; }'

Just getting started with React and Typescript. I'm attempting to extract data from the configuration file based on the input(props), but it seems like Typescript is throwing errors. Any suggestions on how to tackle this issue? config.json { "t ...

Display an API generated popup list using Vue's rendering capabilities

I'm attempting to generate a pop-up within a displayed list using custom content retrieved from an API request. Currently, my code looks like this: <template> <div class="biblio__all"> <a v-for="i in items" ...

What is the most effective method for sharing a form across various components in Angular 5?

I have a primary form within a service named "MainService" (the actual form is much lengthier). Here is an overview- export class MainService { this.mainForm = this.formBuilder.group({ A: ['', Validators.required], B: & ...

The modal feature on ng-bootstrap.github.io is failing to function properly when used with the Bootstrap3 CSS

Struggling to understand why the modal displays when using Bootstrap 4 with ng-bootstrap, but not displaying with Bootstrap 3. ...

The React component using createPortal and having its state managed by its parent will remain static and not refresh upon state modifications

I am facing a problem that can be seen in this live example: https://stackblitz.com/edit/stackblitz-starters-qcvjsz?file=src%2FApp.tsx The issue arises when I pass a list of options to a radio button list, along with the state and setter to a child compon ...

Error message: Angular 7 - Running out of memory due to JavaScript heap

When attempting to run the ng serve command in my Angular 7 application, I encountered an error message stating "JavaScript heap out of memory." After researching various responses on Stack Overflow, it became clear that this issue stems from inadequate m ...

Tips for transferring observable to parent component in angular 2?

I have two components, SearchComponent and RuleListComponent. The Search component is a child of RuleList. https://i.stack.imgur.com/rFlM2.png I need the SearchComponent to retrieve data using APIService. This data should then be passed to RuleList as an ...

Troubleshooting the accessibility issue between Docker node container and Angular/Node.js

After deciding to follow the angular tutorial provided on the angular website, I made the choice to download the "node" image from dockerhub. To ensure proper functionality, I carefully mapped container ports 4200 and 8080 to my physical Windows machine po ...

What is the recommended data type to assign to the `CardElement` when using the `@stripe/react-stripe-js` package in TypeScript?

I'm struggling to determine the correct type to use for this import: import { CardElement } from '@stripe/react-stripe-js'; I have successfully used the types Stripe, StripeElements, and CreateTokenCardData for the stripe and elements props ...

The TypeScript compilation is missing Carousel.d.ts file. To resolve this issue, ensure that it is included in your tsconfig either through the 'files' or 'include' property

While trying to build an Angular application for server-side execution, I encountered the following errors: ERROR in ./src/app/shared/components/carousel/interface/Carousel.d.ts Module build failed: Error: /home/training/Desktop/vishnu/TemplateAppv6/src ...

Can a substring within a string be customized by changing its color or converting it into a different HTML tag when it is defined as a string property?

Let's discuss a scenario where we have a React component that takes a string as a prop: interface MyProps { myInput: string; } export function MyComponent({ myInput }: MyProps) { ... return ( <div> {myInput} </div> ...