2017-05-31 46 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屬性可能會建立由該組件及其後代共享的唯一提供程序;我沒有測試過這個隱含的功能。

如果您正在閱讀此內容,請務必注意,上面使用的通信(指令將自身傳遞到組件)只適用於我的特定情況,並且在對象之間傳遞的消息應該特定於你的實現。