Show child component and its content in parent component based on certain conditions

To show a child component (along with its ContentChildren) within the template of a parent component based on certain conditions.

app.component.html

<parent>
  <child #initial>
    <span>Player</span>
  </child>
  <child label="Intro">
    <span>Intro</span>
  </child>
  <child label="Content">
    <span>Content</span>
  </child>
</tabs>

desired outcome

<parent>
  <child>
    <span>Player</span>
  </child>
</parent>

parent.component.ts

@Component({
  selector: 'parent',
  template: `<!--Display {{current}} and its ContentChildren-->`,
  styleUrls: ['./tabs.component.scss']
})

export class ParentComponent implements OnInit {
  @ContentChildren(ChildComponent) childs;
  @ContentChild("initial") initial;
  @ContentChild("open") current;
  ngOnInit(): void {
    if (this.initial) this.current = this.initial;
  }
}

child.component.ts

@Component({
  selector: 'child',
  template: `<ng-content></ng-content>`,
})

export class ChildComponent {
  @Input() label: string;
}

Approach for parent.component.html

<ng-container *ngFor="let child in childs">
  <child *ngIf="child == current"></child> //ContentChildren as defined in 'app.component.html' are lost now 
</ng-container>

Answer №1

To achieve this functionality, you can utilize the ngSwitch directive.

<parent>
  <div [ngSwitch]="current">
      <child1 *ngSwitchCase="'Intro'" label="Intro">
          <span>Intro</span>
      </child1>

      <child2 *ngSwitchCase="'Content'" label="Content">
          <span>Content</span>
      </child2>
  </div>
</parent>

If you prefer not to use the ngSwitch and want to dynamically change the entire template, you may find the solution in the following link: Dynamic template URLs in Angular 2 Ask

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

Angular-Slickgrid displaying empty data entries

Currently, I am attempting to implement a grid option in my application using the angular slickgrid library. Despite referencing the wiki page for guidance on displaying the grid, I am facing the issue of no data appearing in the grid, and there are no err ...

Utilize MaterialUI's Shadows Type by importing it into your project

In our project, we're using Typescript which is quite particular about the use of any. There's a line of code that goes like this: const shadowArray: any = Array(25).fill('none') which I think was taken from StackOverflow. Everything s ...

Achieving successful npm caching in Azure DevOps for a .net core Angular project

I have a project for a client that involves building an Angular 10/.Net Core project, and it currently takes around 15 minutes. I've been experimenting with caching to optimize the process. Despite trying different configurations, when I add eq(variab ...

Leveraging Component without the need for Import

Is it possible to use a component without re-importing it if it's already declared in AppModule? With 10 or more pages/components to manage, importing each one can be challenging. Here is my app.module.ts import { NgModule, ErrorHandler } from &apos ...

Visual Studio encountering an error with AngularJS TypeScript integration

Hey everyone! I recently installed the angularjs.typescript and jquery.typescript packages from NuGet. However, I'm encountering errors in Visual Studio, as shown in the attached image. I'm using VS 2013 U4 and have updated all extensions and p ...

Can you choose to declare a type in TypeScript, or is it required for every variable

Has anyone encountered a problem similar to this? type B = a ? 'apple' | 'grape' | 'orange' : 'apple' | 'grape'; // This code results in an ERROR! const x = (a: boolean, b: B) => console.log('foo&a ...

Creating a definition for the use of sweet alerts within a service and incorporating them through

Implementing sweet alert for displaying alert messages in angularJS2/typescript. Due to the repetitive nature of this code in different parts of the application, a service was created. @Injectable() export class AlertMessageService { constructor(pr ...

What is the best way to connect an event in Angular 2?

This is an input label. <input type="text" (blur) = "obj.action"/> The obj is an object from the corresponding component, obj.action = preCheck($event). A function in the same component, preCheck(input: any) { code ....}, is being used. Will it wor ...

Leveraging the power of Chart.js and Ng2-Chart within the Cumulocity platform

I'm currently in the process of developing an Angular application for the Cumulocity IoT platform and I wanted to incorporate custom bar charts using Chart.js. Initially, I faced some challenges with this setup but after some research, I came across n ...

Using ng-bootstrap's ngbDatepicker will mark the form as invalid when transitioning from a date value to null

In my Angular application, I am trying to implement bootstrap's ngbDatepicker for a non-required date field. However, when the field contains a date and is then set to null, it causes the form to be marked as invalid. The following code demonstrates ...

Sending Information to Child Component in Angular2

Hi there, I'm currently facing an issue with passing data from a parent Component to a child component controller. Here is the markup code of my parent Component parent.component.html <element [mydata]="Value"></element> By using this ...

Using Svelte with Vite: Unable to import the Writable<T> interface for writable store in TypeScript

Within a Svelte project that was scaffolded using Vite, I am attempting to create a Svelte store in Typescript. However, I am encountering difficulties when trying to import the Writable<T> interface as shown in the code snippet below: import { Writa ...

Angular model-based forms encounter an issue with converting null to an object during asynchronous validation

In my Angular app, I'm working on implementing async validation for a model-based form. I've simplified the form by removing other fields for clarity, but there are additional fields in the actual form. The goal is to check if a username is uniqu ...

Ensure that the input focus is consistently set within the ng-template

When I click on a button in my app, an input element becomes visible. Then, when I click on another button, it gets hidden again. I achieved this functionality using a simple ng-template. However, I encountered a problem - I want the input to automatically ...

What is the best way to set up environments for Google App Engine (GAE

After developing a web app with server and client components, I decided to deploy it to Google Cloud using App Engine. Although the deployment process was successful, the main issue lies in the non-functioning env_variables that are crucial for the applic ...

The type '0 | Element | undefined' cannot be assigned to the type 'Element'

I encountered the following error: An error occurred when trying to render: Type '0 | Element | undefined' is not assignable to type 'Element'. Type 'undefined' is not assignable to type 'ReactElement<any, any>&apo ...

Executing npm prepublish on a complete project

I am facing a situation with some unconventional "local" npm modules that are written in TypeScript and have interdependencies like this: A -> B, C B -> C C -> D When I run npm install, it is crucial for all TypeScript compilation to happen in t ...

An unexpected error has occurred: Uncaught promise rejection with the following message: Assertion error detected - The type provided is not a ComponentType and does not contain the 'ɵcmp' property

I encountered an issue in my Angular app where a link was directing to an external URL. When clicking on that link, I received the following error message in the console: ERROR Error: Uncaught (in promise): Error: ASSERTION ERROR: Type passed in is not Co ...

Nest JS is currently experiencing difficulties with extending multiple classes to include columns from other entities

Currently, I am immersed in a new project that requires me to enhance my entity class by integrating common columns from another class called BASEMODEL. import { Index, PrimaryGeneratedColumn } from "typeorm"; export class BaseModel { @Prima ...

Make the angular component refresh when the back button is pressed

I am working on a TeamSeasonComponent with the URL http://localhost:4200/teams/season/<team_id>. On this page, there are links to other team's pages which would take me to http://localhost:4200/teams/season/team_2_id>. I switch between these ...