指令在子模块中不起作用 [英] Directive doesn't work in a sub module

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

问题描述

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

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'

这是我的 Plunker.

点击转到子项"后检查控制台中的错误

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

推荐答案

那是因为你的指令是在 AppModule 中声明的,而且它只在那里可用.如果你想在两个模块中使用指令,你可以创建 SharedModule 然后从那里声明和导出指令,然后在你的 AppModule 中导入 SharedModule> 和您的 ChildModule:

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 {}

现在您只需要将 SharedModule 添加到 AppModuleChildModule 的导入.

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.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆