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

What could be causing my TypeScript project to only fail in VScode?

After taking a several-week break from my TypeScript-based open-source project, I have returned to fix a bug. However, when running the project in VScode, it suddenly fails and presents legitimate errors that need fixing. What's puzzling is why these ...

Passing dynamic values to nested components within an ngFor loop in Angular

I'm currently facing an issue with a child component inside a ngFor loop where I need to pass dynamic values. Here is what I have attempted so far, but it doesn't seem to be working as expected <div *ngFor="let item of clientOtherDetails& ...

The attribute 'NameNews' is not recognized in the specified type when running ng build --prod

Definition export interface INewsModule{ IDNews:number; IDCategoery:number; NameNews:string; TopicNews:string; DateNews?:Date; ImageCaption:string; ImageName:string ; } Implementation import { Component, OnInit, Input, I ...

Yup will throw an error if both a minimum value is set and the field is also marked

I am attempting to validate my schema using yup: import * as yup from "yup"; let schema = yup.object().shape({ name: yup.string().min(5) }); const x = { name: "" }; // Check validity schema .validate(x, { abortEarly: false }) . ...

encountered an issue when testing a dynamic route in Next.js with postman

I recently created a new API route named route.ts, where I included two different routes. One route retrieves all users from the database, while the other retrieves a specific user based on their ID passed as a query parameter. However, when testing these ...

Encountering a Typescript error when trying to pass a function as a prop that returns SX style

Imagine a scenario where a parent component needs to pass down a function to modify the styles of a reusable child component: const getStyleProps: StyleProps<Theme> = (theme: Theme) => ({ mt: 1, '.Custom-CSS-to-update': { padding ...

What is the best way to iterate through an array within a class in Angular 2?

I am trying to iterate over an array named data, within another array containing 'champions'. Can anyone provide the correct syntax for this? I can successfully loop through all the champions within my IChampion interface, but I'm having tro ...

Error: The function User.findOne is not recognized

Currently, I am in the process of developing a Node.js API and aiming to implement JWT for login functionality. I have successfully set up the model and route, and while testing with Postman using the POST method, an error occurs upon sending the request. ...

The incorrect initial state is causing issues in the Zustand state management on the Next.js server side

While utilizing zustand as a global state manager, I encountered an issue where the persisted states were not being logged correctly in the server side of nextjs pages. The log would only show the default values (which are null) and not the updated state v ...

Efficiently loading Ionic 3 components within a tab with lazy-loading functionality

Need help with adding a new tab to your project using lazy-loading? You can utilize the @IonicPage decorator for setting up a page as the root of a tab. To implement this, create a new page: // module import { NgModule } from '@angular/core'; ...

Tips for presenting SVG symbols using Interpolation within Angular 7 from a JSON document

When it comes to displaying content in Angular 7 components, JSON is used. However, I have encountered a problem while trying to incorporate SVG icons from our UX team into the component using JSON. Using the img tag restricts me from applying a CSS class ...

Issue with Formik compatibility in Next JS 14 Application Structure

I attempted to create a basic validation form using Formik. I meticulously followed their tutorial and example, but unfortunately, the form is not functioning correctly. Despite my efforts, I have been unable to identify a solution (Please correct me if I& ...

Retrieve data from a table within an Angular component

Struggling with the ng2-smart-table library, I am facing challenges in passing values entered in the edit line to a custom component: Refer to the code snippet below for passing Maximum and Minimum Temperature values to the SmartTableEditorFunctionsCompon ...

Troubleshooting issue in Angular 6 mat-select: original array not resetting after filtering values

When filtering an array based on multiple selections from a mat-select, everything works smoothly except for one issue - if I select an option and then deselect it, the entire array disappears from the UI. However, if I select a few other options after tha ...

Update the value in a nested object array by cross-referencing it with a second nested object array and inserting the object into the specified

I have a large array of objects with over 10,000 records. Each object contains an array in a specific key value, which needs to be iterated and compared with another array of objects. If there is a match, I want to replace that value with the corresponding ...

Instead of showing the data in the variable "ionic", there is a display of "[object object]"

Here is the code snippet I'm working with: this.facebook.login(['email', 'public_profile']).then((response: FacebookLoginResponse) => { this.facebook.api('me?fields=id,name,email,first_name,picture.width(720).height( ...

An issue arises in Slate.js when attempting to insert a new node within a specified region, triggering an error

A relevant code snippet: <Slate editor={editor} value={value} onChange={value => { setValue(value); const { selection } = editor; // if nothing is currently selected under the cursor if (select ...

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 ...

What is the best way to iterate through an array of arrays using a foreach loop to calculate the total number of specific properties?

For instance, if YieldCalcValues were to look something like this: [ [ 850, 500 ], [ 3, 6 ], [ 1200, 5000 ], [ 526170, 526170 ] ] I am looking to create a foreach loop that calculates the yield per for each product. How can I accomplish this correctly? l ...

`The Art of Curved Arrows in sigjma.js, typescript, and npm`

I have encountered an issue while trying to draw curved arrows in sigma.js within my TypeScript npm project. The error occurs on the browser/client-side: Uncaught TypeError: Cannot read properties of undefined (reading 'process') at Sigma.pro ...