Tips for dynamically loading a child component and passing data from the child component to the parent component

In my current setup, I have organized the components in such a way that a component named landing-home.component loads another component called

client-registration-form.component
using ViewContainerRef within an <ng-template>, and this rendering occurs on ngAfterViewInit.

The

client-registration-form.component
component is essentially a form containing input fields. It includes a subject defined as:

messageSource = new BehaviorSubject<ClientRegistrationModel>(new ClientRegistrationModel(..))

which stores the data entered into the form. My objective is to capture this data in the parent component landing-home.component.

client-registration-form.component.html

<div>
    <div>
        <span>First Name</span>
        <input type="text" [(ngModel)]='clientRegistrationMoel.firstName'/>
    </div>
    <!-- other fields -->
    <div>
        <input type="button" value="Submit" (click)="OnSubmit()">
    </div>
</div>

client-registration-form.component.ts

import { Component, Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import {ClientRegistrationModel} from '../models/client-registration.model';

@Component({
  selector: 'app-client-registration-form',
  templateUrl: './client-registration-form.component.html'
})
@Injectable()
export class ClientRegistrationFormComponent {
   clientRegistrationMoel : ClientRegistrationModel = new ClientRegistrationModel("","","","");
  constructor() {}
  private messageSource = new BehaviorSubject<ClientRegistrationModel>(new ClientRegistrationModel("","","",""));
  public currentMessage = this.messageSource.asObservable();

  OnSubmit()
  {
    this.messageSource.next(this.clientRegistrationMoel);
  }
}

landing-home.component.html

<div>
    <ng-template #container></ng-template>
</div>
<!-- other parent specific html -->

landing-home.component.js

import { Component, ViewChild, ViewContainerRef, Input, ChangeDetectorRef } from '@angular/core';
import {ClientRegistrationFormComponent} from '../client-registration-form/client-registration-form.component';
import {ClientRegistrationModel} from '../models/client-registration.model';

@Component({
  selector: 'app-landing-home',
  templateUrl: './landing-home.component.html'
})

export class LandingHomeComponent {
  @ViewChild('container', {read: ViewContainerRef}) container!: ViewContainerRef;
  constructor(private clientRegistrationFormComponent: ClientRegistrationFormComponent,
              private changeDetector: ChangeDetectorRef){}

  registrationDetails : ClientRegistrationModel = new ClientRegistrationModel('','','','');
 
  ngAfterViewInit()
  {
    // some condition
    this.container.createComponent(ClientRegistrationFormComponent);
    this.changeDetector.detectChanges(); 
  }
}

My goal with this structure is to have multiple child components, denoted here as A, B, C, etc., along with a parent component P. The appropriate child component will be loaded based on certain conditions when loading the parent P. I am seeking a method to transfer data, like the form inputs or status of form submission, from the currently loaded child component A, B, C.

This code snippet represents an attempt at finding a solution for this scenario, but it may not necessarily stick to the same structure. Most importantly, I want to avoid adding child components with *ngIf due to having a long list of them.

If you have suggestions for a better approach in handling such a situation, please feel free to share.

Answer №1

When a component is created, you have the ability to obtain its reference

this.ref = this.container.createComponent(ClientRegistrationFormComponent);

You can listen to the Subject of the component (and access all its properties)

this.ref.instance.currentMessage.subscribe((res: any) => {
             ...
   })

Check out the StackBlitz example here

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

The utilization of TypeScript featuring a variable that goes by two different names

As I dive into TypeScript code, coming from a Java background, I struggle to grasp the syntax used in this particular example. The snippet of code in question is extracted from the initial Material UI Select sample: const [labelWidth, setLabelWidth] = Rea ...

Displaying a list of items in a dropdown menu that includes both the item's ID and name using angular

I am currently utilizing the angular2-multiselect-dropdown to connect with server values. interface PayerDummyObjType{ id: string; itemName: string; } PayerDummyObjType: PayerDummyObjType[]; PayerDummyObjTypeSelected: PayerDummyObjType[]; dropdownSettin ...

Keeping an object in a multidimensional array based on its ID in Angular 4/Ionic 3 without removing it

Exploring a complex data structure: [{ propertyoutsideid: 1, items: [ {itemId: 1, something: 'something'}. {itemId: 2, something: 'something'}. {itemId: 3, something: 'something'}. ] },{ prope ...

An issue occurred while loading: Uncaught ReferenceError: module is missing from the http://localhost:9876/_karma_webpack_/scripts.js file on line 1

Error image I encountered an error while performing jasmine karma unit testing with angular. Can anyone provide assistance on this issue? Here is my karma.conf.js file: // Karma configuration file, see link for more information //<br> https://karma ...

The Select element in Next.js needs to have an accessible name - it must have a title attribute for improved accessibility

Just starting out with Next.js and Typescript. I'm in the process of rebuilding an app using Next.js, but I've hit a roadblock when trying to split pages and components. The error message that keeps popping up is "Select element must have an acce ...

Do Angular FormControl objects have the capability to accept input values of various types, or are they limited to TypeScript primitive types?

When creating a reactive form in Angular using FormControl objects in a FormGroup, I encountered an issue. While passing primitive arguments as values for an HTML input select control works fine, when passing an object of a self-defined class, the value in ...

Encountering difficulty using a template file as a component template within the Liferay angular portlet

Encountering trouble using a template file as a template for the component in my Liferay angular portlet. It works fine with a regular Angular application. app.component.ts import { Component } from '@angular/core'; @Component({ templateUr ...

Encountering an error in Angular 12 with DomSanitizer when setting the src attribute dynamically for an iframe. The issue arises when trying to set a

Having trouble creating a component to handle YouTube embedded videos? It seems like passing the src as a variable isn't working properly, no matter what is tried. Does anyone have any ideas on what might be going wrong, or if it's a bug in Angul ...

The module './login/servcioprueba1.service' is missing the exported member 'prueba'. Kindly add this member to resolve the issue

I am working on an Angular 8 project that involves a service file. To generate the service, I used the command: ng g s servicioprueba1 After generating the service, I imported it into my code as shown below. Included in Block 2 is the line where I impor ...

Nested self-referencing in Typescript involves a structure where

Please note that the code below has been simplified to highlight a specific issue. The explanation before the code may be lengthy, but it is necessary for clarity. Imagine I have a Foo class that represents a complex object. interface Config { bars:{ ...

What is the best way to customize a MaterialUI outlined input using a global theme overrides file?

I've been working on customizing my theme file with overrides, and I've encountered a strange bug while trying to style the outlined input. It seems like there are two borders appearing when these styles are implemented. https://i.stack.imgur.co ...

Bidirectional data binding in Autocomplete component's matInput

Utilizing a material autocomplete input to search for an article in a database, I originally had a standard input in a table column with the ngModel directive for two-way databinding. To switch this input to an autocomplete input, I followed Angular's ...

Using Typescript to mute audio elements within HTML documents

I have a scenario where I want to mute audio that automatically plays when the screen loads. In order to achieve this, I am attempting to add a button that can toggle the audio mute functionality using Typescript within an Angular4 application. The code sn ...

Limiting the use of the Tab key within a modal dialog box

Currently, I have implemented a modal window that appears when a .btn link is clicked. However, I am facing an issue where users can still navigate through links and buttons in the background by pressing the Tab key. This becomes problematic especially fo ...

Obtaining user profile pictures from Graph API for several users at the same time with the help of RxJs

I have created an ASP.NET Core API that can provide a list of users to an Angular service. The user data returned consists of certain properties like id, firstName, and lastName. My aim is for the Angular service to first fetch this user list from my API ...

Can Next.js accommodate server-side redirection with internationalization?

I'm working on a small Next.js app that has pages accessible only to logged in users. To manage the authenticated routes, I created an HOC (withAuth) that handles redirection on the server side to prevent page flashing on the client side. Everything i ...

Encountering the issue "Unable to define properties of undefined" during Angular unit testing tasks

When attempting to write a unit test case for a dropdown, an error is encountered: TypeError: Cannot set properties of undefined (setting 'ReferralCodes') .spec.ts it("should update the action selecting a value from category drop down", ...

What is the best way to handle typing arguments with different object types in TypeScript?

Currently, I have a function that generates input fields dynamically based on data received from the backend. To ensure proper typing, I've defined interfaces for each type of input field: interface TPField { // CRM id as a hash. id: string nam ...

Angular - handling Observable<T> responses when using Http.post

One issue I encountered was when trying to implement a method that returns an Observable. Within this method, I utilized http.post to send a request to the backend. My goal was to store the JSON object response in an Observable variable and return it. Howe ...

Is the validator in my Angular reactive form malfunctioning?

I have been working on a service where I'm trying to validate the zip code field, but for some reason, the logic (result ? null : { IsInvalid: true }) is not executing. It makes me wonder if there's an issue with the reactive form or if I am usin ...