2017-05-31 45 views
2

让我们假设一个假设的情况。您和我有一个由选择器a-component标识的组件(名为AComponent),以及由选择器[is-modified]标识的指令。如何访问由Angular2中的指令修改的组件?

在另一个组件的定义文件,我们可以使用下面的模板,结合我们的组件和我们的指令,它会修改组件:

<a-component is-modified></a-component> 

documentation for a attribute Directive表明构造给人以ElementRef指令访问,但是没有从ElementRef组件父节点的链接。

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

我试图使用喷射来喷射所需的部件,并改变了ElementRefComponentRef<AComponent>;这给出了ComponentRef没有指定供应商的错误。然后我尝试注入组件AComponent,但也产生了错误。

的文件清楚地表明,“属性的指令,改变元素的外观或行为,组件,或其他指令。”,但我不明白的指令如何获取访问组件它修改。

任何人都可以提供帮助吗?

回答

1

答案在这里找到:Component Interactions

的秘密通信是注入一个服务到构造函数。我延长了组件和指令使用相同的服务:

//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装饰器的providers属性可能会建立由该组件及其后代共享的唯一提供程序;我没有测试过这个隐含的功能。

如果您正在阅读此内容,请务必注意,上面使用的通信(指令将自身传递到组件)只适用于我的特定情况,并且在对象之间传递的消息应该特定于你的实现。