Passing a variable from the second child component to its parent using Angular

Need help with passing variables between two child components

Parent Component:
deposit.component.html

<div>
    <app-new-or-update-deposit [(isOpenedModal)]="isOpenedModal"></app-new-or-update-deposit>
</div>

Deposit Component TypeScript File:

...
export class DepositsComponent implements OnInit {

  public isOpenedModal = false;

  constructor() { }
  ngOnInit() {}

  openModal() {
    this.isOpenedModal = true;
  }
}

First Child Component:
new-or-update-deposit.component.html

<app-modal [(isOpenedModal)]="isOpenedModal">
    <div body>
        Body content
    </div>
    <div footer>
        Footer content
    </div>
</app-modal>

New or Update Deposit Component TypeScript File:

...
export class NewOrUpdateDepositComponent implements OnInit {

  @Input() isOpenedModal: boolean;
  @Output() isOpenedModalChange: EventEmitter<boolean> = new EventEmitter<boolean>();

  constructor() { }
  ngOnInit() { }
}

Second Child Component:
modal.component.html

<div class="modal fade" [ngClass]="isOpenedModal ? 'show modal-block' : ''" tabindex="-1" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" (click)="close()">
                    <span aria-hidden="true">×</span>
                </button>
            </div>
            <ng-content></ng-content>
        </div>
    </div>
</div>
<div class="modal-backdrop fade show" *ngIf="isOpenedModal"></div>

Modal Component TypeScript File:

...
export class ModalComponent implements OnInit {

  @Input() isOpenedModal: boolean;
  @Output() isOpenedModalChange: EventEmitter<boolean> = new EventEmitter<boolean>();

  constructor() { }
  ngOnInit() { }

  close() {
    this.isOpenedModalChange.emit(false)
  }
}

https://i.sstatic.net/a9s8u.jpg

Solution Implemented:
In new-or-update-deposit.component.html

<app-modal [(isOpenedModal)]="isOpenedModal" (isOpenedModalChange)="onIsOpenedModalChange($event)">
    <div body>
        Body content
    </div>
    <div footer>
        Footer content
    </div>
</app-modal>

As isOpenedModalChange is an event, I can call a function using it.

In new-or-update-deposit.component.ts

...
export class NewOrUpdateDepositComponent implements OnInit {

  @Input() isOpenedModal: boolean;
  @Output() isOpenedModalChange: EventEmitter<boolean> = new EventEmitter<boolean>();

  constructor() { }
  ngOnInit() { }

  onIsOpenedModalChange(value) {
    this.isOpenedModalChange.emit(value);
  }
}

Answer №1

If you want, you have the ability to propagate your own events by managing and emitting events on each individual component that the event travels through.

index.html

<app-section (customevent)="onCustomEvent($event)">
</app-section>

section.ts

@Output() customEvent: EventEmitter<number> = new EventEmitter<number>();

onCustomEvent(x: string): void {
  this.customEvent.emit(x);
}

section.html

<app-sub-section (customevent)="onCustomEvent($event)>
</app-sub-section>

and so forth

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

Stop unwanted clicking on inactive buttons in Angular

I want to make sure that disabled buttons cannot be clicked by users who might try to remove the disabled attribute and trigger an action. Currently, I have this code to handle the situation: <button [disabled]="someCondition" (click)="executeAction()" ...

Error TS2307 - Module 'lodash' not found during build process

Latest Update I must apologize for the confusion in my previous explanation of the issue. The errors I encountered were not during the compilation of the Angular application via Gulp, but rather in the Visual Studio 'Errors List'. Fortunately, I ...

Setting up Vue CLI 4 with ESLint, TypeScript, Stylelint for SCSS, and Airbnb rules in the VS Code editor with automatic fixes on save

After struggling with configuring Vue CLI 4 with ESLint, Prettier, Airbnb rules, TypeScript, and Vetur, I found myself at a crossroads. The challenges continued to mount as the nature of the problem evolved from my previous attempts.: How to configure Vue ...

Is the graphql codegen accurately generating the types?

I'm in the process of developing a basic Next.js application with TypeScript by integrating Strapi as a headless CMS. The main goal is to use Strapi and GraphQL, along with TypeScript, to display content on the Next.js app. Within Strapi, there is a ...

The "rest" variable is automatically assigned the type of "any" because it lacks a specified type and is used within its own initializer

Attempting to set up a private route using react router 4 and Typescript. Check out the code I'm working with: type CustomRouteProps<T> = T & { component: any, authRequired: boolean }; function PrivateRoute({ component: Component, authRequ ...

The Firestore query for viewing resources is currently not functioning as expected due to issues with

I'm currently working on implementing the "read" Rules from an array, following the guidelines in this blog post var db = firebase.firestore(); db.collection("_users").where("viewers", "array-contains", myUID) .get() .then((querySnapshot ...

Active Angular component utilizing *ngIf during the programmatically lazy loading of a Module

I find myself in a situation where I need to load numerous components on a specific route within my application. These components are controlled by a logic with *ngIf directives that allow me to show or hide them dynamically. For instance: <div *ngIf=& ...

Unlocking the Secrets of AnimatedInterpolation Values

I have a question about how to access the value of an AnimatedInterpolation in react-native without resorting to calling private code. To achieve this, I first create an animated value and then wrap it in an interpolation like so: animated = new Anima ...

Error: The combination of background color (rgba(22, 15, 15, 0)) and text color (rgba(255, 255, 255, 0.9)) is not recognized as a valid CSS value

Encountering SassError post-upgrade from angular v14 to v15 with npm install ./playground/styles.scss - Error: Module build failed (from ./node_modules/sass-loader/dist/cjs.js): SassError: (background-color: rgba(22, 15, 15, 0), color: rgba(255, 255, 255, ...

Title: How to Build a Dynamic Logo Carousel with React and CSS without External Dependencies

Currently, I am in the process of integrating a logo carousel into my React web application using CSS. My goal is to create a slider that loops infinitely, with the last logo seamlessly transitioning to the first logo and continuing this cycle indefinitely ...

Combining information from two different sources to create a more comprehensive dataset

Two get requests are returning the following data: [{ id: 1, hId: 2 }, { id: 6, hId: 1 }] The second request returns: [{ id: 1, name: 'Bob' }, { id: 2, name: 'Billy' }, { id: 6, name: 'John' }] The object ...

Utilizing Foundation and jQuery in a Next.js web development project

I've been attempting to incorporate Zurb Foundation's scripts into my next js application, but I keep encountering an error message when trying to include the Foundation core. The error I'm seeing is: /Users/alasdair_macrae/Sites/merlin/spa_ ...

Mobile Devices and Local Storage: What You Need to Know for Safe and Efficient Use. Looking for advice from experienced developers

Need help with caching user input on an Angular11 + Firebase app? Let's discuss implementing a caching feature for a dynamic form section that can contain varying fields based on the use case. The goal is to save user input in LocalStorage to ensure ...

Ways to encourage children to adopt a specific trait

Let's discuss a scenario where I have a React functional component like this: const Test = (props: { children: React.ReactElement<{ slot: "content" }> }) => { return <></> } When a child is passed without a sl ...

What is the best way to determine the highest value?

How can I ensure that the data is displayed based on the condition c.date <= this.selectedReport.report_date? The current code snippet if (Math.max(...this.costs.map(c => c.date))){} seems to be causing an issue where no data is being displayed. What ...

What steps are involved in testing an ErrorHandler in express.js?

I am attempting to run a fail case test for this TypeScript function using Sinon, however, I am unsure how to proceed. Can anyone provide assistance? public async findById(id: number): Promise<UserModel> { const user = await this._userModel.fi ...

On production, Heroku fails to load JavaScript files, only allowing CSS files to be loaded. However, the files load successfully when

I've been struggling to find a solution to my problem, so I'm reaching out for some help. I am in the process of deploying my node (express) app to Heroku, but I've encountered an issue where only CSS files from my public folder are being t ...

When the value is empty, MUI Autocomplete will highlight all items

I have encountered a specific issue. I am working on developing a custom Autocomplete Component for filtering purposes. However, I recently came across the following Warning. MUI: The value provided to Autocomplete is invalid. None of the options matc ...

Why is it necessary for the required type of a function parameter to be able to be assigned to

From Optional to Required Type const testFunc = (func: (param: number) => void): void => { func(3); }; testFunc((a?: number) => { console.log(a); }); From Required to Optional Type const testFunc = (func?: (param: number) => void): void = ...

Obtain the precise number input by the user

Seeking assistance with Angular, I am encountering an issue in my application where users input a specific budget (e.g. 18278.85) into a form. However, after submission, the displayed number is rounded to 18278.8 which is not the desired outcome. How can I ...