The custom Local directive in Angular 5 is currently displaying, while my custom global directive remains hidden

First and second directives have been created for a basic CLI framework. The HomePageModule includes the home-page component along with MyFirst.directive.ts, which is referenced in home-page.component.html successfully.

MySecond.directive.ts is similar to MyFirst but at the app.component level. It is declared in app.module.ts, however, it cannot be referenced in home-page.component.html.

The AppModule

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import {HomePageModule} from './home-page/home-page.module';
import {MySecondDirective} from './MySecond.directive';  

@NgModule({
  declarations: [
    AppComponent,
    MySecondDirective  
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HomePageModule
  ],
  providers: [],
  exports: [MySecondDirective],   
  bootstrap: [AppComponent]
})
export class AppModule { }

Home Page Module

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HomePageComponent } from './home-page/home-page.component';
import {MyFirstDirective} from './home-page/MyFirst.directive'; 

@NgModule({
  imports: [
    CommonModule
  ],
  declarations: [
    HomePageComponent,
    MyFirstDirective    
  ],
  exports: [
    HomePageComponent,
    MyFirstDirective    
  ]
})
export class HomePageModule { }

Home Page HTML

<p>
  home-page works!
</p>
<div>
  <h1 myfirst>TESTING</h1>
  <h3 mysecond>Again</h3>
</div>

Program Output https://i.sstatic.net/AQxN5.jpg

Program Structure https://i.sstatic.net/9Dy7X.jpg

MyFirstDirective:

import {Directive, ElementRef, Renderer2} from '@angular/core';

@Directive({
  selector: '[myfirst]'
})
export class MyFirstDirective {

  constructor(private elementRef: ElementRef, private renderer: Renderer2) {
    const nativeElement = elementRef.nativeElement;
    this.renderer.setStyle( nativeElement, 'color', 'red');
    this.renderer.setStyle( nativeElement, 'background-color', 'yellow');
    this.renderer.setStyle( nativeElement, 'border', '1px solid green');
  }
}

MySecondDirective:

import {Directive, ElementRef, Renderer2} from '@angular/core';

@Directive({
  selector: '[mysecond]'
})
export class MySecondDirective {

  constructor(private elementRef: ElementRef, private renderer: Renderer2) {
    const nativeElement = elementRef.nativeElement;
    this.renderer.setStyle( nativeElement, 'color', 'green');
    this.renderer.setStyle( nativeElement, 'background-color', 'orange');
    this.renderer.setStyle( nativeElement, 'border', '2px solid red');
  }
}

Thank you! - Chuck

Answer №1

Angular modules do not follow a hierarchical structure.

Simply registering your directive in the root AppModule informs Angular that it is being used, but you still need to import it into any module where you intend to utilize the directive.

It is generally advised against exporting anything from the root AppModule since it is not meant to be imported into other modules.

To make your components/directives accessible across multiple modules within your application, consider creating a SharedModule, export the necessary components/directives there, and then import it into any module that requires them.

A common misconception about imported modules is the belief that they establish a hierarchy. Developers might assume that a module importing others becomes the parent module for its imports. However, this is not the case. During compilation, all modules are merged together, erasing any hierarchical relationship between the importing and imported modules.

from Angular In Depth

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

Utilizing Filters (Pipes) in Angular 2 Components without Involving the DOM Filters

When working in Angular 1, we have the ability to use filters in both the DOM and Typescript/Javascript. However, when using Angular 2, we utilize pipes for similar functionality, but these pipes can only be accessed within the DOM. Is there a different ap ...

The next/image component encounters issues when transitioning a project from JavaScript to TypeScript

I am currently in the process of transitioning my personal website from a Next.js JavaScript project to TypeScript. In the previous version, I used a placeholder background image loaded with the next/image system: <Image src="/filename.jpg" ...

Best Practices for Retrieving and Passing Data within a Resolver | Angular 10/11

Currently, I am working on fetching data into a component before it loads to customize some settings. However, I find the concept of resolver a bit confusing in terms of what it returns and how to interpret it. I am struggling with getting the correct dat ...

Trouble with expanding multiple rows in an Angular nested mat table functionality

I recently built a nested mat-table grid using Angular Material. However, I am facing an issue where only one row can be expanded at a time. I am looking for a solution to allow multiple rows to be expanded simultaneously without automatically collapsing t ...

Verifying Whether Objects in TypeScript File Adhere to a Certain Interface

Currently, I am in the process of developing a procedure that scans through a collection of *.ts files within a directory to identify those containing a class that implements a specific interface. While my preference is to be able to detect multiple classe ...

What is the process for importing scripts?

After setting up Angular to experiment with, I made sure to have node.js and npm installed. Next, I globally installed the @angular/cli package and created a new project called testproject. Following that, I ran npm install and npm start, which all worked ...

Deleting an element from an array in Mongodb using Angular

My question remains unanswered: Delete an element from an array of an array in MongoDb In the process of creating a basic MEAN application similar to Stack Overflow, I have encountered an issue. Within my application, there are articles with upvotes and d ...

Guide to crafting a reply using nestjs exception filters with nestfastify

I'm facing a challenge with writing custom HTTP responses from NestJS exception filters. Currently, I am using the Nest Fastify framework instead of Express. I have created custom exception filters to handle UserNotFoundException in the following mann ...

Cypress eliminating the "X-CSRFToken" header

There seems to be an issue with the Cypress test runner where it is removing X-CSRFToken from the request header, leading to a 403 Forbidden error. I have compared the headers between a manual run and a Cypress test run, and you can see the difference in t ...

The Angular ngFor loop seems to be stuck in an endless cycle while trying to display

I'm currently in the process of creating a Logbox for my web application. It is designed to receive an Array of logs and display them row by row within a div. I am utilizing ngFor to iterate through my Array of logs and then present them. However, I& ...

Encountering issues with loading resources within the Angular production environment

Currently, I am in the process of deploying an Angular-CLI app onto a server. After using the command ng build --environment=production, the build was successful without encountering any errors. Subsequently, running the ng serve command did not throw any ...

After updating my Ionic Android App to Angular 12, it got stuck on a blank white screen with an error message stating: "goog.getLocale is

After successfully upgrading my Ionic App with Angular 11 to version 12, everything seemed fine when running it in the browser. However, when attempting to launch it on an Android device, I encountered a white screen after the splash-screen vanished. My t ...

Tips for aligning mat-card in the center using Angular Material

My login card, designed with Angular materials, seems to be sticking to the left side of the page when I view it. I've tried using flex and layout-align="center center" but can't seem to get the card centered on the page. What could I be doing ...

Why is it that AoT chooses to lower this value?

I am facing an issue with environment variables in my angular 5 project. I have been using a common.ts file in the environment/ folder like this: environment.prod.ts import common from './common/common'; export const environment: any = { ... c ...

Angular 11 throws an error stating that the argument of type 'null' cannot be assigned to a parameter of type 'HttpClient'

As I embark on my journey to becoming a developer, I encounter a problem when passing a null argument as shown below: todos.component.spec.ts import { TodosComponent } from './todos.component'; import { TodoService } from './todo.servic ...

Navigating through ionic2 with angularjs2 using for-each loops

I developed an application using IONIC-2 Beta version and I am interested in incorporating a for-each loop. Can anyone advise if it is possible to use for each in Angular-V2? Thank you. ...

How can I call an external function in Typescript within an Angular 2 project using C3 js with the c3

I've been struggling with a specific issue for quite some time now, but I can't seem to pinpoint the exact problem. I'm not sure if it's related to Angular or C3. Oddly enough, I'm unable to execute my method within the c3.generat ...

Guide to adding annotations to a PDF document using Angular 2

As a novice in the field of Angular development, I am seeking guidance. Currently, I have an application that displays PDF files. My goal is to be able to annotate and make changes on these PDF files by adding drawings such as circles, lines, or text. Ho ...

Establishing the initial state within the constructor of a React Component utilizing a generic state

I have encountered an issue with React and Typescript. I am working on a component that utilizes two generics for props and state. interface Props { foo: string; } interface State { bar: string; } class Foo< P extends Props = Props, S e ...

What is the best way to monitor parameter changes in a nested route?

I need assistance with managing routes const routes: Routes = [ { path: 'home', component: HomeComponent }, { path: 'explore', component: ExploreComponent, children: [ { path: '', component: ProductListC ...