What could be the reason my component is not displaying the ContentChild associated with a directive?

It appears that utilizing a directive to target a content child from another directive is the recommended approach (source).

However, why isn't my component able to recognize the component marked with the directive?

./my.component.ts

import {
  Component,
  Directive,
  ContentChild,
  AfterContentInit
} from "@angular/core";

@Directive({
  selector: "[trigger]"
})
export class TriggerDirective {}

@Component({
  selector: "app-my-component",
  template: ` <ng-content></ng-content> `
})
export class MyComponent implements AfterContentInit {

  @ContentChild(TriggerDirective) trigger: TriggerDirective;

  ngAfterContentInit() {
    console.log("===> ", this.trigger);
    // output: '===> undefined'
  }
}

./my.module.ts

import { NgModule } from "@angular/core";
import { MyComponent, TriggerDirective } from "./my.component";

@NgModule({
  declarations: [MyComponent, TriggerDirective], // declared here
  exports: [MyComponent]
})
export class MyModule {}

./app.component.ts

import { Component } from "@angular/core";

@Component({
  selector: "app-root",
  template: `
    <h1>Title inside app component.</h1>
    <app-my-component>
      <button #trigger>Click me</button>
    </app-my-component>
  `
})
export class AppComponent {}

./app.module.ts

import { BrowserModule } from "@angular/platform-browser";
import { NgModule } from "@angular/core";

import { AppComponent } from "./app.component";
import { MyModule } from "../my-component/my.module";

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, MyModule], // imported module here
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}

Answer №1

After receiving guidance from @Mike S, the comprehensive answer is as follows:

./app.component.ts

import { Component } from "@angular/core";

@Component({
selector: "app-root",
template: `
  <h1>Title inside app component.</h1>
  <app-my-component (submit)="doSomething($event)">
    <!-- 1. use the directive without '#' since that would make it a reference variable -->
      <button trigger>Click me</but
    <button trigger>Click me</button>
  </app-my-component>
`
})
export class AppComponent {}

./trigger.directive.ts

import { Directive } from "@angular/core";

@Directive({
  selector: "[trigger]"
})
export class TriggerDirective {}

./my.component.ts

import { Component, ContentChild, AfterContentInit } from "@angular/core";
import { TriggerDirective } from "./trigger.directive";

@Component({
  selector: "app-my-component",
  template: ` <ng-content></ng-content> `
})
export class MyComponent implements AfterContentInit {
  // 2. declare it as a content child
  @ContentChild(TriggerDirective) trigger: TriggerDirective;

  ngAfterContentInit() {
    console.log("==>", this.trigger);
  }
}

./my.module.ts

  1. Declare the trigger, and export it for usage in the module where the component lives where you'd like to use it.
import { NgModule } from "@angular/core";
import { MyComponent } from "./my.component";
import { TriggerDirective } from "./trigger.directive";

@NgModule({
  declarations: [MyComponent, TriggerDirective],  
  exports: [MyComponent, TriggerDirective] 
});
export class MyModule {}

./app.module.ts

  1. And finally ensure the entire module is included in the module where you're using it.
import { BrowserModule } from "@angular/platform-browser";
import { NgModule } from "@angular/core";
import { AppComponent } from "./app.component";
import { MyModule } from "../my-component/my.module";

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, MyModule],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}

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

Methods for closing a modal popup on button click

In my AppComponent, there is a login button that triggers a SigninComponent modal popup when clicked. I am trying to figure out how to close the opened modal popup when a button is clicked. Below is the code snippet: app.component.html <ng-template # ...

Establishing the Default Dropdown Value in ABP Framework Using Angular UI Dynamic Forms

Currently, I am utilizing the ABP framework along with Angular UI to work on dynamic forms. One specific aspect of my work involves implementing a dropdown as shown below: const timeZoneProp = new FormProp<IdentityUserDto>({ type: ePropType.Enum, ...

Angular 6 - Unlocking the Secrets of Filtered Results

I need help accessing the filteredArray in my .ts component. Currently, it is only accessible within the ng-container. <ng-container *ngIf="(userList | filter: 'name' : value) as filteredArray"> <tr *ngFor="let user of filteredArray ...

Ways to retrieve root context within a Vue Composition API in Vue 3.0 + TypeScript

Looking to develop a TypeScript wrapper function that can trigger toast notifications using a composition function, following the guidelines outlined in Vue 3.0's Composition API RFC. In this instance, we are utilizing BootstrapVue v2.0 for toast not ...

npm encountered a 401 Unauthorized error while trying to access the latest version of @angular/cli

When attempting to run the npm install -g @angular/cli command in admin mode from the command window, I encountered the error message: npm ERR! 401 Unauthorized: @angular/cli@latest A colleague of mine did not face any issues with this command, and I hav ...

Changing a password on Firebase using Angular 5

I am in the process of developing a settings feature for user accounts on an application I've been working on. One key functionality I want to include is the ability for users to update their password directly from the account settings page. To enable ...

Dealing with errors when implementing an Angular 2 route guard that returns an Observable of type boolean can be a

My route guard is implemented as follows: @Injectable() export class AuthGuard implements CanActivate { constructor(private router: Router, private authenticationSvc: AuthenticationService) { } canActivate(): Observable<boolean> { return this. ...

The default route in Angular is always preloaded and ready to be

I currently have two routes available: home [ '' ] about [ 'about' ] Upon directly accessing the /about route in my browser, I've observed the following: The home module is preloaded even though I requested /about. The URL gets ...

Is there a solution for resolving the Element Implicitness and Lack of Index Signature Error?

I encountered an issue with specialCodes[letter]. It mentions that The element implicitly has an 'any' type because the expression of type 'string' cannot be used to index type and No index signature with a parameter of type 'strin ...

How can I implement a redirect back to the previous query page post-authentication in Next.js 13?

To enhance security, whenever a user tries to access a protected route, I plan to automatically redirect them to the login page. Once they successfully log in, they will be redirected back to the original protected route they were trying to access. When w ...

Automatically shift focus to the next input when reaching the maximum length in Angular

Looking for a smoother way to focus the next input element in Angular without manually specifying which one. Here's my current HTML setup... <div class="mb-2 digit-insert d-flex align-items-center"> <div class="confirmation-group d-flex"&g ...

I'm struggling with finding an answer to this question: "What is the most effective way to conduct a

I'm experimenting with a file upload. I decided to encapsulate the FileReader() inside an observable based on information I found in this discussion thread: onFileSelected(event: any) { this.importJsonFileToString(event.target.files[0]) .p ...

Encountering a problem where the alert popup does not appear when refreshing Chrome for the first time on the homepage in an Angular application

Firstly, I want to express my gratitude for your response to my previous inquiry. I am currently encountering an issue. When landing on the homepage for the first time, the alert popup does not work. However, once inside the application, it functions prop ...

Is it possible for npm to assist in determining the appropriate version of Primeng that is compatible with Angular 16 dependencies

While trying to add primeng to my project, I ran into an error message: npm i primeng npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email-protection" class="__cf_email__ ...

Angular Floating Panels: A Guide to Creating Dynamic User Interfaces

In the process of developing an angular app, I require a dock-able panel. After researching available controls online, I found them difficult to use and they compromised our screen layout. As a result, I am considering building a custom dock panel from s ...

Can you explain the distinction between ng test and ng e2e?

Concerned that someone might close my question, I struggled to find a satisfactory answer. Perhaps it's due to my limited knowledge in the Angular 2+ realm or maybe I misunderstood something. From what I gathered after dabbling in Hello World project ...

Ordering numbers in Angular2 using a custom pipe

In my Angular2 project, I am attempting to organize an array of strings based on numerical values using a custom pipe that was not authored by me. The code for the pipe is provided below: import { Pipe, PipeTransform } from "@angular/core"; @Pipe( { name ...

Interacting with the Dropdown feature on the page causes the body of the page to shift

I am encountering an issue with 2 dropdowns in Datatables used to filter content. The problem arises when a dropdown is positioned on the right side of the page, causing a shift to the left by approximately 10px. Conversely, if the dropdown is placed on th ...

Subtracting Arrays Containing Duplicates

Imagine having two arrays defined like this: const A = ['Mo', 'Tu', 'We', 'Thu', 'Fr'] const B = ['Mo', 'Mo', 'Mo', 'Tu', 'Thu', 'Fr', 'Sa&ap ...

In order to emphasize the chosen list item following a component refresh

SCENARIO: Let's consider a scenario where I have a component named list, responsible for displaying a list of all customers. Within this list, certain conditions are set up as follows: 1) Initially, the 1st list-item (e.g. Customer 1) is selected by ...