Angular 5 Event Emitter and Output fail to trigger parent function

I've exhaustively researched and attempted all available options to no avail. Specifically, I have a button designed to switch between light and dark modes by toggling a boolean value passed to the parent component to alter the background color of the webpage. Here's what I'm working on:

Child

This is the HTML file:

<mat-toolbar class="mat-elevation-z5" color="primary">
<h1 class="first">firstName</h1><h1 class="second">SecondName</h1>
<button class="dark-mode" *ngIf="isLight" matTooltip="Bit too bright?" matTooltipPosition="before" (click)="changeMode()"><mat-icon>brightness_low</mat-icon></button>
<button class="light-mode" *ngIf="isDark" matTooltip="Bit too dark?" matTooltipPosition="before" (click)="changeMode()"><mat-icon>brightness_high</mat-icon></button>
</mat-toolbar>

This is the TypeScript (.ts) file:

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

@Component({
 selector: 'main',
 templateUrl: './main.component.html',
 styleUrls: ['./main.component.scss']
})
export class MainComponent implements OnInit {
  @Output() isDarkMode = new EventEmitter<boolean>();

  isLight: boolean;
  isDark: boolean;

  ngOnInit() {
    this.isDark = false;
    this.isLight = true;
  }

  changeMode(){
    if(this.isDark) {
      this.isDarkMode.emit(false);
      this.isLight = true;
      this.isDark = false;
    } else {
      this.isDarkMode.emit(true);
      this.isLight = false;
      this.isDark = true;
    }
  }
}

Parent

<main (isDarkMode)="isDarkMode($event)"></main>

This is the TypeScript (.ts) file for the parent:

import { Component, EventEmitter } from '@angular/core';
import * as jQuery from 'jquery';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {

  isDarkMode(event: boolean) {
    console.log(event);
  }
}

The issue I'm facing is that my console.log statement isn't being displayed, suggesting that the event isn't being emitted as expected?

Any assistance would be greatly appreciated. I don't believe I'm overlooking anything obvious...

Thanks

Answer №1

To trigger your event in the child component, make sure to use the changeMode() method for emitting. Adjust your initialization function by adding a call to changeMode():

  ngOnInit() {
    this.isDark = false;
    this.isLight = true;
    this.changeMode();
  }

Verify that the console logs when changeMode() is executed.

If you have a button to switch to dark mode, include the following in your HTML template:

<button (click)="changeMode()">Change</button>

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 process of overriding a method from an abstract class that employs generics for typing?

In my quest to develop an abstract class with an abstract static method, I find myself wanting to override this method in a concrete class. The static nature of the method stems from its responsibility to create a 'copy' from a database model and ...

The property 'text' cannot be defined as it is undefined

xml code screenshotError screenshotI'm facing an issue where I am trying to bind a label with my code and set its text, but every time I run the code, I get an error message saying 'Cannot set property 'text' of undefined'. I have ...

Tips for incorporating CSS 4 custom properties into Angular components

Exploring the new possibilities of CSS 4 with custom properties, my goal is to utilize them in Angular. Traditionally, custom properties are used in the following manner: <div style="--custom:red;"> <div style="background-color: var(--custom ...

Issue with Angular 7 and rxjs - Once catchError is triggered, the subscription stops receiving any further values

Consider the following code snippet: this.service1 .getValues() .pipe( mergeMap(response => this.service2.getMoreValues(response.id)), catchError(err => of({})) ) .subscribe(response) => { console.log(response) }); The issu ...

Creating a type alias for a union type in typescript and then exporting it

Is there a way to export something similar to the following: export TypeA | TypeB as TypeAB; and define a variable of TypeAB that could be either TypeA or TypeB: import {TypeAB} from './typeab'; let ab: TypeAB; ...

Dynamic loading in React Plugin Architecture allows for flexibility in organizing and incorporating

My goal is to develop a Single Page Application on the client side that incorporates a plugin architecture. The requirement is for users to be able to place a package in a designated folder, which will then be loaded by the server after a restart. These pl ...

Where should I place the function URL and the path to credentials.json when attempting to call a Google Cloud Function with CloudFunctionsServiceClient?

I found this code snippet on here: /** * TODO(developer): Uncomment these variables before running the sample. */ /** * Required. The name of the function to be called. */ // const name = 'abc123' /** * Required. Input to ...

I am currently facing an issue related to the length property. It is showing an ERROR TypeError: Cannot read property 'length' of undefined

Is it recommended to set the length to be inherited from Angular right? If so, why am I getting this error: "MyPostsComponent.html: 7 ERROR TypeError: Cannot read the 'length' of undefined property" when fileList.length is greater than 0? onFile ...

The module 'ngx-cookie-service' could not be located

I am currently working with Angular 12 and recently I installed a cookie service using the following command: npm install --save ngx-cookie-service Within my app.module.ts file, when I try to import the 'CookieService' like so: import { Cookie ...

Discover the ultimate strategy to achieve optimal performance with the wheel

How can I dynamically obtain the changing top position when a user moves their mouse over an element? I want to perform some checks whenever the user scrolls up, so I tried this code: HostListener('window:wheel', ['$event']) onWindowS ...

Drag and drop files effortlessly with Angular framework

Just getting started with Angular and typescript. I need to be able to select single or multiple video files by dragging and dropping using Angular. I found a helpful reference here: https://stackblitz.com/edit/angular-rksspi?file=src%2Fapp%2Fapp.componen ...

Exceeded maximum stack size error encountered in Ionic 2 Tab bar functionality

When I attempt to incorporate a tab bar into my application, an error message saying "Maximum call stack size exceeded" is displayed Profile.html <ion-tabs> <ion-tab tabIcon="water" tabTitle="Water" ></ion-tab> <ion-tab tabI ...

Exploring the Implementation of Validation Pipe in class-validator

I am currently exploring how to effectively utilize my validation pipe in combination with class-validator on an API call. My DTO is decorated with class-validator decorators and is performing as anticipated. However, I am interested in utilizing the &apo ...

Strategies for resolving the TypeScript error code TS7009?

I am currently new to Typescript programming and in the learning phase. I encountered a problem while coding and received an error in the backend console. Here is the code snippet that caused the error: function employee(id:number,name:string) { this.i ...

Exploring the Power of Observables in Angular 2: Chaining and

Hi there! I'm relatively new to Angular and still getting the hang of observables. While I'm pretty comfortable with promises, I'd like to dive deeper into using observables. Let me give you a quick rundown of what I've been working on ...

Creating a custom function in TypeScript to redefine the functionality of the `in` operator

I am looking to create a custom function that mimics the behavior of the in operator in TypeScript, utilizing user-defined type guards. (To see an example, check out Lodash's has function.) When using n in x where n is a string literal or string l ...

Using regular expressions in TypeScript to declare modules

Is there a more efficient method to declare multiple modules in TypeScript? An example of the code I am trying to simplify is: declare module '*.png'; declare module '*.jpg'; declare module '*.gif'; declare module '*.svg ...

Encountering an Issue: Unable to connect with 'ngModel' as it is not recognized as a valid property for 'input' even after importing FormsModule

Despite importing FormsModule in my app.module.ts, I am still encountering the following error message. 'Cannot bind to 'ngModel' since it isn't a known property of 'input' I have thoroughly reviewed similar posts, but unf ...

Leveraging the power of Angular's conditional content projection with the versatile ng-container

I've been browsing through the official Angular documentation and came across the section on conditional content projection. In this part, there's a code snippet that looks like this: <div *ngIf="expanded" [id]="contentId&qu ...

Tips for activating scroll feature for certain section of an HTML page

For the styling of my page, I'm utilizing Scss and am facing an issue related to setting up scrolling for specific sections of an HTML page. You can check out the image reference here. During a scroll event, I want to ensure that the Categories (left ...