让我们假设一个假设的情况。您和我有一个由选择器a-component
标识的组件(命名为 ACOMPONTION (,而选择器[is-modified]
标识的指令。
在另一个组件的定义文件中,我们使用以下模板结合了我们的组件和指令,该模板修改了组件:
<a-component is-modified></a-component>
属性的文档指令表明构造函数可以访问 elementRef 的指令访问,但是没有来自 Elemans> elementRef 的链接组件 parent。
export class IsModifiedDirective
{
constructor( elementReference : ElementRef )
{
console.log( elementReference );
//no connection appears to exist between elementReference and the component
//also: ElementRef has security risks, so it should be avoided.
debugger;
}
}
我尝试使用注射注入必要的组件,并将ElementRef
更改为ComponentRef<AComponent>
;这给出了一个错误,即没有为 ComponentRef 指定提供商。然后,我尝试注入组件AComponent
,但也会产生错误。
文档清楚地表明"属性指令 - 改变元素的外观或行为, component 或其他指令。",但是我看不到该指令如何获得对 component 它修改了。
任何人都可以提供帮助吗?
答案已在此处找到:组件交互
通信的秘诀是将服务注入构造函数。我扩展了组件和使用相同服务的指令:
//The Component Definition (Psuedocode)
@Component(
{
...,
providers: [ AService ],
...
}
)
export class AComponent
{
constructor( commonService : AService )
{
let comp : AComponent = this;
commonService.serviceAnnouncement$.subscribe(
(msg)=>{
//msg can be anything we like, in my specific instance,
//I passed a reference to the directive instance
comp.doSomethingWithMsg( msg );
}
);
}
}
-
//The Directive Definition (Psuedocode)
@Directive(...)
export class IsModifiedDirective
{
constructor( commonService : AService )
{
commonService.announceSomething( this );
}
}
-
//The Service Definition (Psuedocode)
import { Subject } from 'rxjs/Subject';
@Injectable(...)
export class AService
{
private source = new Subject<MsgType>();
serviceAnnouncement$ = this.source.toObservable();
announceSomething( msg : MsgType )
{
this.source.next( msg );
}
}
上面的类别存在于其自己的文件中。导入和其他代码大部分被排除在外,以避免使显示器混乱。他们的关键是,这些对象可以将自己的实例传递给听取共享服务的其他对象。该文档表明,@component Decorator的providers
属性可能会建立该组件及其后代共享的独特提供商。我尚未测试此隐含功能。
如果您正在阅读本文,请务必注意,上面使用的通信(指令将自己传递给组件,仅适用于我的特定情况(,并且对象之间传递的消息应针对您实施。