[英]How do I call shared directive's method in Angular2 RC5 typescript?
I have custom directive in my code that several components should consume. 我的代码中有自定义指令,有几个组件应该使用它。 I registered it in my app.module and thus can use it in my templates. 我在app.module中注册了它,因此可以在我的模板中使用它。
But my problem is that I see no way to call this directive's methods from components code as it doesn't import and register it in directives: []
any longer? 但我的问题是我看不到从组件代码调用这个指令的方法,因为它不导入并在directives: []
注册它directives: []
?
Eg Here when I don't share the directive it is used like 例如,当我不共享指令时,就像使用它一样
import { Modal } from '../bootstrap';
@Component({
templateUrl: '.....html',
directives: [Modal]
})
export class MyComponent {
constructor(private modal: Modal) {
this.modal.show();
}
}
but when I extracted these components into the separate modules and moved this directive to a shared module, import ..
and directives: [...]
are gone and I cannot have private modal: Modal
injected to call its method show
. 但是当我将这些组件提取到单独的模块中并将此指令移动到共享模块时, import ..
和directives: [...]
已经消失,我不能拥有private modal: Modal
注入调用其方法show
。 If I keep them, I get Error: Type Modal is part of the declarations of 2 modules: ...
error message. 如果我保留它们,我会得到Error: Type Modal is part of the declarations of 2 modules: ...
错误消息。
Add it to [providers]
in your AppModule: 将其添加到AppModule中的[providers]
:
providers: [Modal]
Then you need to import that service in component that should consume it and it will work, there is no need to add it as directives, for example: 然后,您需要在应该使用它的组件中导入该服务并且它将起作用,不需要将其添加为指令,例如:
import { Modal } from '../bootstrap';
You can then add it to constructor: 然后,您可以将其添加到构造函数:
constructor (private modal: Modal)
Now you can use that service: 现在您可以使用该服务:
this.modal.show()
Edit: 编辑:
Updated the answer to match the code you provided. 更新了答案以匹配您提供的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.