Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 - Directive not working when not declared in the same module

I have a directive and I want to use it in multiple modules. Declaring it on each modules produces an error. Thus, I tried to declare it in a shared module and import this shared module to other modules. However, it didn't work. It only works when it is declared exactly on the component's own module.

Here is my SharedModule:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { GeneralDataService } from './general-data.service';
import {ModalDirective} from '../directives/modal.directive';

    @NgModule({
      imports: [
        CommonModule
      ],
      providers: [GeneralDataService],
      declarations: [ModalDirective]
    })
    export class SharedModule { }

And the module that I want to use ModalDirective:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MyComponent } from './patient.component';
import {SharedModule} from '../shared/shared.module';
@NgModule({
  imports: [
    CommonModule,
    SharedModule
  ],
  providers: [  ],
  declarations: [ MyComponent ]
})
export class MyModule { }

In MyComponent component:

export class MyComponent implements OnInit, AfterViewInit {

  @ViewChild(ModalDirective) modal: ModalDirective;

  ...
}

modal in MyComponent is undefined (even in ngAfterViewInit) if ModalDirective is not declared in MyModule. Anyone knows how to fix this?

like image 880
Bünyamin Sarıgül Avatar asked Feb 09 '17 13:02

Bünyamin Sarıgül


People also ask

Why directive is not working in Angular?

Put a debugger; statement inside the constructor of your directive. Then you'll know for sure when it's working and you can remove it. Make sure you have selector: '[magicFeature]' and not selector: 'magicFeature' Sometimes you need to restart your ng serve to make sure everything is refreshed.

How to use a shared module in Angular?

Sharing moduleslink You can put commonly used directives, pipes, and components into one module and then import just that module wherever you need it in other parts of your application. Notice the following: It imports the CommonModule because the module's component needs common directives.

What is the decorator to declare a class as directive in Angular?

Directivelink. Decorator that marks a class as an Angular directive. You can define your own directives to attach custom behavior to elements in the DOM.


1 Answers

In your SharedModule you need to export the ModalDirective

...

@NgModule{(
   ...
   exports: [ModalDirective]
)}
export class SharedModule { ... }

See docs on shared modules for more info

like image 163
Fredrik Lundin Avatar answered Oct 17 '22 23:10

Fredrik Lundin