Transferring data from a child component to a parent using EventEmitter and dynamic components in Angular 6

Hey there, I am currently working on a dynamic form utilizing a dynamic component loader. The parent component structure is as follows:

<div class="item-form-block-content">
    <div class="form-block">
       <ng-template pf-host></ng-template>
    </div>
</div>

Within this structure, there are multiple child components that are placed inside the ng-template. My goal is to pass data from the child components to the parent component by utilizing an EventEmitter.

For instance, let's consider one of the child components:

<input type="text" [(ngModel)]="value" (change)="onValueChange(value)"/>

Here is the corresponding controller code:

export class childComp implements OnInit {
@Output() someVar = new EventEmitter<any>();

onValueChange(val: any) {
    this.someVar.emit(val);
}}

The question now is, how can I successfully pass the someVar variable from the child component to the parent component?

Answer №1

To handle communication between child and parent components in Angular, you can register an event listener on the child component within the parent component's template.

<child (someVar)="doSomething($event)"></child>

Define the method doSomething(value: any) {} in the parent component to process the emitted values.

Technical Implementation

For a more detailed approach based on specific requirements, check out a solution proposed in this GitHub post. This method involves manually setting up event listeners in the parent component:

class ParentComponent implements AfterContentInit {

    @ContentChildren(ChildComponent)  
    List<ChildComponent> children;

    void onSomeValEvent() {
        console.log("Event received!");
    }

    ngAfterContentInit() {
        this.children.forEach((ChildComponent child) {
            child.someVal.listen((_) => onSomeValEvent());
        });
    }

}

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 is the solution for the error stating "Unable to locate a declaration file for the module 'request-context'."?

I am currently working on three different files: index.js, index.main.js, and app.js. My goal is to use request-context to extract a variable from index.main.js and pass it to index.js. Within my app.js file, located in the server folder, I have the follo ...

Is it possible to configure a custom timezone for the Angular Material datepicker feature?

I am currently working on an Angular 7 application and I have encountered a challenge with the date field. In this particular field, I am utilizing the Angular Material Datepicker input. However, I have noticed that the datepicker automatically captures th ...

Tips for successfully utilizing hyphens when passing an object property as an argument

Does anyone know how to pass an object property with a hyphen in it as an argument? I'm having trouble with this issue. Object { "section-id": 1, ... } HTML <div *ngFor="let section of sections" (trackScrollLeave)="leave(section.sectio ...

Is there a way I can conduct a search that includes both uppercase and lowercase characters simultaneously?

My current task is to create a search function that can search for elements in both lower and upper case, regardless of the case typed in by the user. I have attempted to implement a search feature that covers both upper and lower case scenarios, but it s ...

Async pipe in Angular does not work with my custom observables

I've been trying to implement the async pipe in my template, but I'm encountering difficulties retrieving data from my API. To store and retrieve the data, I have utilized a behavior subject to create an observable. However, when I attempt to dis ...

Tips for Passing On Parent tabindex Value to Children

Is there a way to propagate a parent's tabindex value to all of its children without individually setting tabindex for each child? Here is an example code snippet: <div id="app"> <div tabindex="2" class="parent-sec ...

Deactivate a variable during operation

I have a unique component called book-smart that has the functionality to display either book-update or book-create based on the availability of a BookDto in my book.service. The update feature can be accessed by clicking a button in a table, while the cre ...

Unable to generate the 'validator' property on the string 'userForm' while utilizing the component factory

Currently, I am in the process of creating a component factory to generate my login form dynamically. Initially, I encountered an issue where the FormGroup was not recognized by the form where I was introducing my component. After resolving that with the h ...

Obtaining the IP address upon page load in Angular 4: A step-by-step guide

In the midst of my Angular4 project, I'm on a mission to fetch the system IP address upon page load and send it over to the API for storage in a MSSQL database. However, each time the page loads, two rows are inserted and the IP address is coming up a ...

What is the return type of the Array.prototype.sort() method in Typescript?

I have created a custom type for arrays that are considered "sorted" like this: type Sorted<T> = T[]; This serves as a reminder for developers to provide a sorted array of any type and ensure the sorting themselves. Although I understand that Types ...

TypeScript async function that returns a Promise using jQuery

Currently, I am facing a challenge in building an MVC controller in TypeScript as I am struggling to make my async method return a deferred promise. Here is the signature of my function: static async GetMatches(input: string, loc?: LatLng):JQueryPromise& ...

changing an array into json format using TypeScript

Looking to convert an array into JSON using TypeScript. How can I achieve the desired result shown below? let array = ['element1', 'element2', 'element3'] result = [{"value": "element1"}, {"value": "element2"}, {"value": "el ...

`As the input value for these methods`

I am encountering an issue when trying to pass in this.value as a method argument. The field values are all strings and the constructor arguments are also all strings, so I don't understand why it's not working. When I attempt to pass in this.cla ...

Can you identify the specific function type passed through props?

interface IProps { handleCloseModal: React.MouseEventHandler<HTMLButtonElement> returnFunction: () => void; } export default function Modal({ children, returnFunction, handleCloseModal, }: React.PropsWithChildren<IProps>) { cons ...

Developing a REST API for a component with 18 interconnected elements

Currently, I am developing a REST API to expose a table to an Angular frontend, and I've encountered a unique challenge: The data required for display is spread across 10 different tables besides the main entity (referred to as "Ticket"). Retrieving t ...

Encountering the issue of receiving "undefined" when utilizing the http .get() method for the first time in Angular 2

When working in Angular, I am attempting to extract data from an endpoint. Below is the service code: export class VideosService { result; constructor(private http: Http, public router: Router) { } getVideos() { this.http.get('http://local ...

Tips on showcasing multiple values using Angular 4?

Using angular 4 and spring boot, I retrieve a list of records from spring boot to angular 4 but only display a single object in the form. How can I list multiple values in the search box? component.ts: Within this component, all the values are retrieved b ...

Is there a way to replicate the tree structure of an array of objects into a different one while modifying the copied attributes?

Is there a way to replicate the tree structure of an array of objects to another one in TypeScript, with different or fewer attributes on the cloned version? Here's an example: [ { "name":"root_1", "extradata&qu ...

Updating a one-to-one relationship in TypeORM with Node.js and TypeScript can be achieved by following these steps

I am working with two entities, one is called Filter and the other is Dataset. They have a one-to-one relationship. I need help in updating the Filter entity based on Dataset using Repository with promises. The code is written in a file named node.ts. Th ...

Exploring Angular: Retrieving a Variable in TypeScript Using a String Passed from HTML

Is there a way to retrieve the value of a variable in .TS by passing its name as a string from HTML? For example: In HTML: <div id="myID"><button mat-button (click)="foo('name')">Export to Excel</button></div> In TS v ...