指令在子模块中不起作用

指令在子模块中不起作用

本文介绍了指令在子模块中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法使该指令在延迟加载的模块中工作.我已经阅读了文档,并且只是将指令添加到了主模块的声明数组中.该指令在该模块上按预期工作,但在延迟加载的模块中不起作用.它甚至可以防止由于模板错误而打开延迟加载的模块:

I can't make the directive work in a lazy loaded module. I've read the documentation and I simply added the directive into declarations array of my main module. The directive works as expected at that module, but it doesn't work in lazy loaded modules. It even prevents lazy loaded module to be opened because of the template error:

Can't bind to 'myHighlight' since it isn't a known property of 'p'

这是我的柱塞.

点击转到孩子"后在控制台中检查错误

Check out errors in console after clicking 'go to child'

推荐答案

这是因为您的指令在AppModule中声明,并且仅在此处可用.如果要在两个模块中同时使用指令,则可以创建SharedModule,然后从那里声明和导出指令,然后在AppModuleChildModule中导入SharedModule:

That's because your directive is declared in AppModuleand it's only available there. If you want to use directive in both modules, you can create SharedModule and then declare and export directive from there, and then import SharedModule in your AppModule and your ChildModule:

@NgModule({
  declarations: [ HighlightDirective ],
  exports: [ HighlightDirective ]
})

export class SharedModule {}

现在,您只需要在AppModuleChildModule的导入中添加SharedModule.

Now you just need to add SharedModule to AppModule's and ChildModule's imports.

注意:

您必须从AppModule的声明中删除您的指令,因为它只能被声明一次.

You have to remove your directive from AppModule's declarations since it can only be declared once.

这篇关于指令在子模块中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 03:36