How to invoke a method in a nested Angular 2 component

Previous solutions to my issue are outdated. I have a header component

import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx'; 

import { AuthenticationService } from '../_services/Authentication.Service';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
  loading = false;
  error = '';
  isLoggedIn = false;
  showMessageWindow = false;
  messageType: string = "";
  messageText: string = "";
  public currentUser: any = null;

  constructor(private _auth: AuthenticationService, private router: Router) { }

  ngOnInit() {
    if(this._auth.isLoggedIn()) {
      this.isLoggedIn = true;
    }
    else {
      this._auth.logout();
      this.isLoggedIn = false;
      this.router.navigate(['/']);
    }
  }

  showMessage(message: string, type: string) {
    this.messageText = message;
    this.messageType = type;
    this.showMessageWindow = true;
  }
}

The header component is responsible for managing navigation based on log-in status. It also contains a warning/alert feature. Since not all pages use the header, it must be imported into specific components with

<app-header></app-header>
.

Below is an example of a component utilizing the header.
import { Component, OnInit } from '@angular/core';
import { HeaderComponent } from '../header/Header.Component';
import { Router, ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-census',
  templateUrl: './census.component.html',
  styleUrls: ['./census.component.css']
})
export class CensusComponent implements OnInit {

  constructor( private router: Router, private activatedRoute: ActivatedRoute) { }

  ngOnInit() {

  }

}

I am attempting to call the showMessage() method from the header component within a different component. However, I am facing challenges in referencing the embedded component. Despite trying various methods, I haven't had much success. My main question pertains to how to correctly reference the embedded component when using separate HTML files.

When adding

  @ViewChild(HeaderComponent)
  private header: HeaderComponent;

to my CensusComponent, I receive a warning:

WARNING in ./src/app/header/Header.Component.ts
There are multiple modules with names that only differ in casing.
This can lead to unexpected behavior when compiling on a filesystem with other case-semantic.
Use equal casing. Compare these module identifiers:

Answer №1

Utilizing the ViewChild decorator factory is essential

// Take a look at this sample component utilizing the header.

import { ViewChild } from '@angular/core';
import { Component, OnInit } from '@angular/core';
import { HeaderComponent } from '../header/Header.Component';
import { Router, ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-census',
  templateUrl: './census.component.html',
  styleUrls: ['./census.component.css']
})
export class CensusComponent implements OnInit {

  // By specifying `HeaderComponent` as an argument, the framework knows how to connect to the child 
  // component whose constructor function is `HeaderComponent`
  @ViewChild(HeaderComponent)
  header: HeaderComponent;

  constructor(readonly router: Router, readonly activatedRoute: ActivatedRoute) {}

  ngOnInit() {
    this.header.showMessage('an error occurred!', 'error');
  }
}

The warning message you are encountering:

WARNING in ./src/app/header/Header.Component.ts
There are multiple modules with names that only differ in casing.
This can lead to unexpected behavior when compiling on a filesystem with other case-semantic.
Use equal casing. Compare these module identifiers:

is unrelated to your code logic.

Essentially, it indicates that when you imported header/Header.component for registration in your NgModule, the import was done using different casing. For instance, header/header.component

This issue can and should be resolved. Ensure consistency in the casing of all imports.

I suggest using lowercase file names and lowercase module specifiers consistently. A quick search and replace operation should rectify this.

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

Adding a button label value to a FormGroup in Angular

I've been working on a contact form that includes inputs and a dropdown selection. To handle the dropdown, I decided to use the ng-Bootstrap library which involves a button, dropdown menu, and dropdown items. However, I'm facing difficulties inte ...

How to prevent duplicate database entries in Angular forms?

Currently, I am working on a project using Angular and TypeScript. The goal is to retrieve a list of users from an API and allow for the addition of new users. However, I am struggling with determining how to verify if a user with a specific name already e ...

Utilize an alias to define the SCSS path in an Angular-CLI library project

I am in the process of developing a library project using angular-cli. I have been following the guidelines outlined in the angular documentation. This has resulted in the creation of two main folders: one is located at ./root/src/app, where I can showcase ...

Enhancing supertest functionality with Typescript

Currently, I am working on extending the functionality of supertest. After referencing a solution from Extending SuperTest, I was able to implement the following example using javascript: const request = require('supertest'); const Test = reque ...

When using Angular forms, the password or username may be duplicated if entered twice when pressing the

I am currently working on a basic username and password form using Angular. Here's the template I have: <label class="welcome-content">Username:</label> <input #userName type="text" id="txtLoginUsername" (keyup.enter)="loginUser(userNa ...

Is it possible to dynamically close the parent modal based on input from the child component?

As I follow a tutorial, I am working on importing the stripe function from two js files. The goal is to display my stripe payment in a modal. However, I am unsure how to close the modal once I receive a successful payment message in the child. Below are s ...

What is the method for bypassing libraries while troubleshooting Angular code in Visual Studio Code?

While debugging my Angular project, I keep getting into @angular/core and ts-lib which are large files with many steps. Is there a way to skip over external code during the debugging process? Below is my launch.json configuration: "version": &qu ...

Limit the category to a specific subset of strings

Looking for a way to implement literal type restrictions without using type aliases: const foo = (a: 'string', b: 'string') => { } foo("123", "abc") // should fail foo("123" as 'string', "abc" as 'string') I pr ...

Is it possible to efficiently share sessionStorage among multiple tabs in Angular 2 and access it right away?

My Current Knowledge: I have discovered a way to share sessionStorage between browser tabs by using the solution provided here: browser sessionStorage. share between tabs? Tools I Am Using: Angular 2 (v2.4.4) with TypeScript on Angular CLI base The ...

Optimizing Your Approach for Rolling Out Test and Development Application Versions on Google Compute Platform

Google Computing Platform I currently have an Angular (2) application and a Node.js middleware (Loopback) running as Services in an App Engine within my project. We are using a Compute Engine to run PostgreSQL for our database in the same project. Our Go ...

Error: Module '/node_modules/.vite/deps/react-pro-sidebar.js?v=913080ef' does not export 'ProSidebar' as requested

Using the pro-side-bar library in React is causing an issue for me. When I run the code, the console shows the following error using the dev tools: Uncaught SyntaxError: The requested module '/node_modules/.vite/deps/react-pro-sidebar.js?v=913080ef& ...

Utilizing the reduce() function to simultaneously assign values to two variables from data input

Looking to simplify the following function using reduce(), as the operations for variables selectedEnrolled and selectedNotEnrolled are quite similar. I attempted to use map(), but since I wasn't returning anything, it led to unintended side effects ...

Building a theme with TypeScript in React

As I embark on my React project, I've been tasked with creating a CSS using TypeScript while referring to the color palette diagram provided below. Utilizing createMuiTheme to build the theme, I've realized that there are various possible conditi ...

Updating Your Child: A Guide

Currently, I have a component that makes reference to a child component with the following code cc: TheChildComponent; @ViewChild('theChildComponent') set details(content: TheChildComponent) { this.cc = content; }; TheChi ...

Step-by-step guide to designing a basic pagination/carousel using div elements in HTML and Angular 2

Hey there! I'm currently working on a project with an *ngFor in my template that generates multiple divs. <div *ngFor="let item of widgets" class="page-content widget-item"> <div>{{content}} </div> </div> I'd like to i ...

Is it possible to include multiple eventTypes in a single function call?

I have created a function in my service which looks like this: public refresh(area: string) { this.eventEmitter.emit({ area }); } The area parameter is used to update all child components when triggered by a click event in the parent. // Child Comp ...

Angular 13's ng serve does not support the keyword "id" for schema ID. Instead, it is recommended to use "$id" to define the schema ID

After successfully upgrading my application from Angular 11 to 13, I encountered some issues while trying to transition from version 12 to 13. Whenever I attempt to run ng serve or ng build, I am faced with the following error: An unhandled exception occ ...

Filtering database results from an Angular component

I am currently working on an Angular component and I have a result variable in the .ts file that stores data retrieved from the database. My goal is to filter this result variable to display only 20 records and sort them by date either in ascending or de ...

Guide on how to utilize jest for mocking MongoDB manager in typescript

Is there a way to return a mongodb.connection.db() type value and mock its collection for testing purposes? I have implemented a mongoClient connection and use its db() function. If everything is set up correctly, I should be able to access the collections ...