Directive in Ionic 3

Viewed 6789

In app on Ionic 2 Directive declared in app.module.ts.

But in Ionic 3 (lazy load) this Directive not working. I try to import Directive in component module, such:

...
import { TabindexDirective } from '../../../app/tabindex.directive';

@NgModule({
  declarations: [
    ...
    TabindexDirective,
  ],
  imports: [
   ...
  ],
  exports: [
    ...
  ],
})
export class SignupModule {}

This code works fine, but then i Import this directive in another component module, i have error:

Type GoComponent is part of the declarations of 2 modules: SignupModule and AddPageModule! Please consider moving GoComponent to a higher module that imports

How to fix it and use Directives in Ionic 3?

5 Answers

Declaring directives in component has changed in ionic -3, actually it will bind by the module itself.

The solution to this problem is as following

Solution - 1

Declare and export all directive in one module, so you can use it in your module/ionic page

import { NgModule } from '@angular/core';
import { TabindexDirective } from '../../../app/tabindex.directive';
@NgModule({
    declarations: [TabindexDirective],
    imports: [],
    exports: [TabindexDirective]
})
export class SharedDirectives {}

and in your module you can import SharedDirectives

Solution - 2

Bind the directive in your module and import to child component using .forchild();

import { TabindexDirective } from '../../../app/tabindex.directive';
@NgModule({
  declarations: [
    TabindexDirective,
  ],
  imports: [
    ...
    IonicPageModule.forChild(TabindexDirective)
  ],

})
export class SignupModule {}

I have experienced the exact same error recently, except with Angular components, when trying to build in --prod mode. I finally got it fixed by removing the .module.ts files from certain directives and components.

I marked your question as a duplicate, so please redirect to this link for several solutions to your issue.

I don't want to replicate my answer, but here is the idea :

import { IonicModule; IonicPageModule } from 'ionic-angular';
import { MyApp } from './app.component';
import { MyComponent } from '../directives/my-directive/my-directive';

@NgModule({
  imports: [
    IonicModule.forRoot(MyApp),
    IonicPageModule.forChild(MyComponent) // Here
  ],
  declarations: [MyApp, MyComponent]
})

Original answer : https://stackoverflow.com/a/47253126/1311952

Related