2017-05-31 10 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; 
    } 
} 

Iは、必要な成分を注入する注入を使用しようとしたComponentRef<AComponent>ElementRefを変え。これにより、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属性がそのコンポーネントとその子孫によって共有される一意のプロバイダを確立するかもしれないことを示唆しています。私はこの暗黙の特徴をテストしていない。

これを読んでいる場合は、上記で使用されている指示がコンポーネントに渡される通信は、特定のケースでのみ機能し、オブジェクト間で渡されるメッセージは、あなたの実装。

関連する問題