Incorporate a child component into a parent component using Angular

I am looking for a neat solution to dynamically add a child component child to a parent component parent, using a method similar to jQuery's append. This should happen every time a specific event occurs. Ideally, starting with:

<parent></parent>

The goal is to end up with:

<parent>
   <child></child>
</parent>

It's worth noting that the type of the child component will not be known until the event triggers.

A possible structure could be defined as follows:

import { Component} from '@angular/core';
import { OnMyEvent} from 'onmyevent';

@Component({selector: 'odd-child'})
export class OddChildComponent {}  

@Component({selector: 'even-child'})
export class EvenChildComponent {}    

@Component({selector: 'parent'})
export class ParentComponent implements OnMyEvent {    
  constructor() {}

  onMyEvent(n) {
    if (n%2==0){
      this.append(new EvenChildComponent())
    } else {
      this.append(new OddChildComponent())
    }
  }

}

With jQuery, the process would look something like this:

<div id="parent"></div>

Script:

document.body.onmyevent = function(e, n) {
    if(n%2==0){
        child = $("div.even-child")
    } else {
        child = $("div.odd-child")
    }
    $("#parent").append(child)
}

If the event with parameter n=4 is triggered, the result would be:

<div id="parent">
    <div class="even-child"></div>
</div>

How can this functionality be achieved?

Answer №1

import {EventEmitter, OnInit} from "@angular/core";
@Component({selector: 'parent-component'})
export class ParentComponent implements OnInit{
  currentItem = null
  itemChange: EventEmitter<string>;
  constructor() {
   this.itemChange = new EventEmitter<string>();
  }
  ngOnInit(){
   this.itemChange.subscribe(item=> {
      this.currentItem = item;
   })
  }

}

<parent-component>
   <child *ngIf="currentItem === 'item type 1'"></child>
   <another-child *ngIf="currentItem === 'item type 2'"></another-child>
</parent-component>

To trigger the event, you can use:

this.itemChange.emit("item type 1")
If you plan to use this event outside of the parent component, consider creating a service for it.

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

Troubleshooting the inability of Angular to retrieve variable properties in TypeScript

Here is the code I am currently working with: data:IQuest[]|any=[]; ngOnInit(){ this.getData(); console.log(this.data[1].Question); } getData(){ let url = "http://127.0.0.1:5153/Quests"; this.http.get(url).subscribe(data=>{ this.d ...

Uploading files in Angular 5 with additional properties of other objects

I am facing a challenge with uploading a file as part of a property to an object within a form. Most documentations I have come across only focus on services that handle standalone files. In my case, I have a form with various text inputs and date pickers, ...

Angular encountered an error while attempting to manage a base service that was not defined

My service involves extending a base service to handle error data effectively. For instance import { CurrentUserService } from './current-user.service'; import { CONFIG } from './../shared/base-urls'; import { BaseServiceService } fro ...

Enforcing uniform data types in nested objects in TypeScript

Currently, I am in need of generating a list of constants. For instance, const Days = { YESTERDAY: -1, TODAY: 0, TOMORROW: 1, } I am looking for a method to restrict the types of all properties within Days. In other words, if I attempt to add a pr ...

Suggestions for importing by Typescript/VS Code

Imagine you have a file called a.ts that contains 4 named imports: export const one = 1 export const two = 2 export const three = 3 export const four = 4 Next, you have a file named b.ts and you want to import some variables from a.ts. import {} from &a ...

Tips for generating cautionary claims in Playwright TypeScript assessments for non-urgent issues?

Is there a way to implement warnings instead of failures for non-critical assertions in Playwright TypeScript tests? Currently, while working on Playwright tests using TypeScript, I am searching for a solution to handle assertions that would issue warning ...

JavaScript code that displays values that are not equal

Here is a code snippet that checks whether two arrays of objects are equal or not. How can we enhance this code to log which answer is not matching? The structure of the arrays: arrayA represents user answered questions, while arrayB contains correct answ ...

The SetInterval function will continue to run within a web component even after the corresponding element has been removed from the

I am currently engaged in developing a straightforward application that coordinates multiple web components. Among these components, there is one that contains a setInterval function. Interestingly, the function continues to run even after the component it ...

Obtaining the value of an ion-toggle in Ionic2 using the ionChange

Below is the toggle I am referring to: <ion-toggle (ionChange)="notify(value)"></ion-toggle> I am looking for a way to retrieve the value of the toggle when it is clicked in order to pass it as a parameter to the notify method. Any suggestion ...

Having troubles with Angular 2 subscription functionality?

I am attempting to launch a modal window that has its template and logic in a separate component. My goal is to accomplish this by subscribing to an observable, but I am encountering issues. Below is my code: Method within the component where I want to tr ...

Is it possible to extract the value from a switchMap observable instead of just receiving the observable itself?

I am currently working on creating a unique in-memory singleton that stores the vendor being viewed by a user. A guard is implemented on all specific routes to capture the parameter: canActivate( route: ActivatedRouteSnapshot, state: RouterStateSnapsh ...

Subtracting Arrays Containing Duplicates

Imagine having two arrays defined like this: const A = ['Mo', 'Tu', 'We', 'Thu', 'Fr'] const B = ['Mo', 'Mo', 'Mo', 'Tu', 'Thu', 'Fr', 'Sa&ap ...

Angular 2 - update browsing history by replacing instead of adding to it

Is it possible to replace the history instead of pushing a new one in Angular 2's new router (rc.1)? For instance, suppose I am in a question list (/questions), then open a new modal in a new route (/questions/add). After adding a new question, I nav ...

Do you need to have typing or definition files for each JavaScript library you utilize in TypeScript?

Do you need typings for every JavaScript library used in TypeScript? If not, how can you eliminate errors and utilize a library that doesn't have available definition files? import { NotificationContainer, NotificationManager } from 'react-notif ...

TypeScript error TS6053: Unable to locate file '.ts'

I encountered the following issue: Error TS6053: Could not find file 'xxx.ts'. Oddly enough, the file compiled without any issues yesterday. However, today it seems to be causing trouble. To troubleshoot, I ran a simple test: class HelloWorl ...

I am experiencing an issue with my service provider when it comes to displaying multiple navigator stacks

Currently, I am developing a provider to manage the user's state across different views. The primary function of this provider is to display either one stack navigator or another based on whether a certain variable is filled or empty. This setup allow ...

What is the best way to retrieve a value from an object using a promise after a certain period of time

During an event, I receive a user object. When I try to access the user._properties.uid value before using setTimeout, it returns as undefined. However, when I implement setTimeout, the value is successfully fetched after a few seconds. Is there a way to ...

Ensuring the Component is Navigated to Before Activation in Angular 4 - Can

Is there a way to determine which component is being requested by the user in CanActivate for authentication purposes? Instead of checking the URL as shown below, I would like to do something like checking if(route.component instanceof MyComponent). I am ...

Exploring Event Propagation in Angular2 without using a directive

Is there a way to propagate events from within a route to outside the <router-outlet></router-outlet>? I'm facing a scenario where I need HomeComponent to notify the root component about something, but it's not a direct child of app.c ...

Unable to locate the identifier 'TextDecoder' in TypeScript version 2.7

In the development of my Angular 6 application with TypeScript 2.7, I encountered an issue when trying to implement the TextDecoder native function. Upon running ng build --aot, I received the error: error TS2304: Cannot find name 'TextDecoder'. ...