Angular: Managing changes in child component fields

I have integrated a child component in my Angular application which contains two Boolean fields. I aim to respond promptly in the parent component whenever these values change.

///////////////////////////////////////////////////////
// Child Component
///////////////////////////////////////////////////////
@Component({
  selector: 'critical',
  template: `<div class="blueBorder"><h1>This is a critical component</h1></div>`,
  styles: [`h1 { font-family: Lato; } .blueBorder {border: 1px solid blue;}`],
})
export class CriticalComponent {
  error: boolean = false;
  warning: boolean = false;
}
///////////////////////////////////////////////////////
// Parent Component
///////////////////////////////////////////////////////
@Component({
  selector: 'my-app',
  template: '<critical #criticalCmp></critical>',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  @ViewChild('criticalCmp') criticalCmp: CriticalComponent;

  onErrorsOrWarningsInCriticalComponent(): void {
    // Execute this method each time the values in the critical-component are updated
    // Perform API calls, log information, or other actions here
  }
}

How can I achieve this functionality?

To demonstrate, you can view a StackBlitz example here: https://stackblitz.com/edit/angular-ivy-hpn8qy?file=src/app/app.component.ts

Answer №1

Utilizing a setter in conjunction with an Output is one way to achieve the desired functionality.

Parent Component:

import { Component, ViewChild } from '@angular/core';
import { CriticalComponent } from './critical.component';

@Component({
  selector: 'my-app',
  template: '<critical #criticalCmp (errorChanged)="errorChanged($event)"></critical>',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  @ViewChild('criticalCmp') criticalCmp: CriticalComponent;

  onErrorsOrWarningsInCriticalComponent(): void {
    // This method will be triggered whenever there are changes in the critical-component
    // Perform actions like calling services, logging, etc. here
  }

  errorChanged(isError: boolean) {
    if(isError){
      this.onErrorsOrWarningsInCriticalComponent();
    }
  }
}

Child Component:

import { Component, EventEmitter, Input, Output } from '@angular/core';

@Component({
  selector: 'critical',
  template: `<div class="blueBorder"><h1>This is a critical component</h1></div>`,
  styles: [`h1 { font-family: Lato; } .blueBorder {border: 1px solid blue;}`],
})
export class CriticalComponent {
  @Output() 
  errorChanged = new EventEmitter();
  set error(val: boolean) {
    this._error = val;
    this.errorChanged.next(val);
  };
  get error() {
    return this._error;
  }
  warning: boolean = false;

  private _error: boolean = false;
}

Effective communication between components can be achieved through various methods, for further reference check out the Angular documentation: https://angular.io/guide/component-interaction

Answer №2

If you're looking to take a proactive approach using Observables, here's a suggestion.

Create two BehaviorSubjects named error and warning, and set their initial values like this:

error = new BehaviorSubject(false);
warning = new BehaviorSubject(false);

Combine them using combineLatest with @Output() to trigger emissions when the values change:

@Output() myBooleans = combineLatest({
  error: this.error.asObservable(),
  warning: this.warning.asObservable(),
}).pipe(skip(1));

To ignore the initial emission, I'm using skip(1).

The parent component can listen for changes in these values:

<critical (myBooleans)="onErrorsOrWarningsInCriticalComponent($event)"></critical>

When you need to update either value in the child component, simply call: this.error.next() or this.warning.next().

I also recommend creating an interface for this object to properly type your data.

You can find the solution implemented in this STACKBLITZ link.

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

Node's TypeScript parser loses the order of same name-tags when converting XML to JSON

I've experimented with xml2js and fast-xml-parser and received similar results from both (in different formats, but that's not the focus here) This specific example is from fast-xml-parser Here's the XML data: <test version="1" ...

Why are the icon pictures not displaying in Angular's mat-icon-button?

Recently, I stumbled upon a snippet of code in an Angular project that caught my eye. Naturally, I decided to incorporate it into my own program: <div style="text-align:center"> <a mat-icon-button class="btn-google-plus" href="http://google.com ...

Exploring the use of static properties in JSDoc Classes

Is there a way for me to set up this correctly? https://i.sstatic.net/dn75F.png I am trying to document the id property using the static classes _Test.list, but I can't seem to find the right method with intellisense in vscode. So any number not comi ...

Can a universal type be designed for application across various types?

I've got this function: function stackPlayer(stack){ } The stack parameter can have one of the following forms only: a function that takes req, res, and next as arguments. a function that takes req, res, and next as arguments, and returns a functio ...

Calculating the total sum of values within a JSON array

Here is the data that I am working with: input1 = [{ "201609": 5, "201610": 7, "201611": 9, "201612": 10, "FY17": 24, "metric": "metric1", "careerLevelGroups": [{ "201609": 3, "201610": 6, "201611": ...

What method does Angular use to distinguish between familiar elements and unfamiliar ones?

<bar>- it is a tag with a random name, not officially recognized, so it makes sense that it is considered invalid <div> is valid because it is a standard HTML element - does Angular have a documented list of standard elements? Where can I fin ...

A guide on implementing a universal service to seamlessly incorporate jQuery datatable across all pages in an Angular application

I am looking to streamline the process of integrating jQuery datatables with export buttons across multiple pages. After installing jQuery and typings for jQuery, I made sure to include jQuery in the types array of tsconfig as well. "types": [ "jquery" ...

Creating a collapsible sidebar feature in Angular 2

Currently in the process of converting an HTML jQuery AdminLTE dashboard to Angular 2 In the past, I would hide and show the sidebar using toggle() in jQuery. Now I'm wondering how to achieve the same functionality in Angular 2. I am utilizing the ...

Leveraging information within Typescript and Angular

Can anyone assist me with an Angular 5 request? http.get(baseUrl + 'api/Student/Students1') .subscribe(result => { this.std = (result as Students[]); }, error => console.error(error)); This is th ...

The error message "Cannot redeclare block-scoped variable 'tz'" is shown when trying to use Ionic 2 along with angular-moment-timezone

Today, I installed angular-moment-timezone in my Ionic project and everything was working fine. However, after removing the node_modules folder and then running npm i, I started getting errors whenever I tried to run ionic serve. These are the errors I am ...

What steps can be taken to ensure that only users with "admin" status have the ability to edit certain data within a Firebase document?

Within my Angular application, I have implemented Firestore for storing user profiles. Currently, the structure looks like this: /profiles/{uid}/: { displayName: "Luigi",//--> Only editable by Luigi email: "<a href="/cdn-cgi/l/email-protecti ...

What is the process of defining an object enum in a declarations document?

Here is a sample javascript file named test.js: const someType = { val1: "myvalue", val2: "myothervalue" }; function sampleFunction(param) { return 1; } function sampleFunction2(param) { return 2; } export {someType, sampleFunction, sampleFunct ...

Bringing in a TypeScript module to an Angular component

Having trouble with including a specific library in my component Here is the code for my component which uses geolib as the library: import { Component, OnInit } from '@angular/core'; import { StationsService } from '../../../services/stati ...

Updating the value of a variable in Angular2 as you slide an HTML slider

Currently, I have integrated an HTML round slider into my Angular6 application. The detailed implementation can be found at: https://www.w3schools.com/howto/howto_js_rangeslider.asp This is how the .html file is set up: <span style="font-size: 130px;" ...

Issue with routerLink not activating properly when used within ngFor directive

For the past three days, I've been dealing with an interesting challenge. It all started with this particular HTML code snippet: <mat-list-item *ngFor="let setting of SideBarLinks" [ngStyle]="{'display': setting[&ap ...

Experimenting with Cesium using Jasmine (Angular TypeScript)

I have a TypeScript app built using Angular that incorporates Cesium: cesium-container.component.ts import { Component, ElementRef } from '@angular/core'; import { Viewer } from 'cesium'; import { SomeOtherCesiumService } from 'sr ...

Why ngModel Behaves Oddly in Angular 2

myList: any; ngOnInit(){ this.myList = [ {id: 1, name: 'a'}, {id: 2, name: 'b'}, {id: 3, name: 'c'}, {id: 4, name: 'd'}, ]; } In my HTML file: <input *ngFor="let l of myLi ...

Utilizing Angular's Module Federation with Webpack to address duplication in Reactive Forms FormControl

In the process of developing a microfrontend application utilizing Angular ModuleFederation Application. Within one of the micro apps, there is a reactive form with the following structure: <input type="text" [formControl]="email" / ...

What is the correct way to effectively produce a detailed post template?

I'm currently working on a project to enhance my Angular skills. In this project, I am fetching and displaying posts from https://jsonplaceholder.typicode.com/. My goal is to create a detailed post template accessible through a URL like localhost:3000 ...

Alert: Prop type validation error: The `component` prop provided to `ForwardRef(Link)` is invalid

We are facing an issue with our NextJS app where it works fine in production, and locally it renders correctly. However, we are encountering some unsightly warnings that we are trying to suppress. client.js:1 Warning: Failed prop type: Invalid prop `compon ...