2016-02-23 36 views
3

我有兩個組件這樣的:角2 - 獲取組件實例

@Component({ 
    selector: 'comp1', 
    template: `<h1>{{ custom_text }}</h2>` 
}) 
export class Comp1 { 
    custom_text:string; 
    constructor(text:string) { 
     this.custom_text = text; 
    } 
} 

/*********************************************/ 

@Component({ 
    selector: 'comp2', 
    directives: [Comp1], 
    template: ` 
    <b>Comp 2</b> 
    <comp1></comp1> 
    ` 
}) 
export class Comp2 { 
    constructor() { 
     // ... 
     // How to send my own text to comp1 from comp2 
     // ... 
    } 
} 

是否有可能從COMP1送我自己的文字COMP2?

是否有可能從comp2獲取comp1實例?

謝謝。

+0

看看這個http://blog.mgechev.com/2016/01/23/angular2-viewchildren-contentchildren-difference-viewproviders – TGH

回答

1

是的,這是很容易做到的是,

結帳教程:MULTIPLE COMPONENTS 的Angular2教程的第3部分,看看如何發送輸入。

@Component({ 
    selector: 'comp1', 
    template: `<h1>{{customText}}</h2>`, 
    inputs: ['customText'] 
}) 
export class Comp1 { 
    public customText:string; 
    constructor(text:string) { 
     this.customText= text; 
    } 

// ngOnChange to make sure the component is in sync with inputs changes in parent 
ngOnChanges() { 
     this.customText= text; 
    } 
} 

/*********************************************/ 

@Component({ 
    selector: 'comp2', 
    directives: [Comp1], 
    template: ` 
    <b>Comp 2</b> 
    <comp1 customText = "My Custom Test"></comp1> 
    ` 
}) 
export class Comp2 { 
    constructor() { 
    } 
} 

試一試,讓我知道它是如何去的。

+0

完美,非常感謝你...... –

+0

這難道不是拋出錯誤?:'構造函數(文本:字符串){' –

+0

是的。但僅僅是一個例子。 –

4

COMP2是COMP1的父母,所以

  • 從孩子將數據發送到父(COMP1到COMP2)添加OutputProperty孩子:
    @Output() someEvent = newEventEmitter();
    emit()事件就可以了:this.someEvent.emit('some text');
    的parent將需要綁定到輸出屬性/事件:<comp2 (someEvent)="someHandler()"></comp2>
  • 以獲得對子組件實例的引用(comp2獲取對comp1的引用),請在comp2中使用@ViewChild@Query@ViewChild(Comp1) viewChild:comp1;然後,您可以在ngAfterViewInit()中訪問this.comp1,或稍後訪問組件的生命週期。
+0

我開始認爲這是一個輸出案例,但如果你看他的代碼,他正試圖做一個輸入案例並表達錯誤。我喜歡你在發射器上的回答,但通常我會發現輸出使得組件很難改變,因爲我們需要維護回調契約,通常我會更改後端中的更改以保存和傳播更改,但對於最小狀態數據,回調是精細。 –