[英]Angular 2 child to parent communication without using Event Emmiter
[英]Parent to child communication without event
我在子組件中有字符串參數,需要在父組件中顯示。 它應該在頁面加載時完成。 所以,不是點擊或任何其他事件。
你是如何做到這一點的?
到目前為止,我沒有找到任何適合我的解決方案的答案。
因此,排除通過事件進行通信,您有以下選擇:
通過共享服務進行通信。 這是一種常見的策略,無需示例。
將對象從父對象傳遞給子對象。 如果子級更新對象引用上的屬性,則父級也會看到更新后的值(盡管沒有通知)。
演示: https : //stackblitz.com/edit/angular-h7h5xl
原則:
父級創建一個對象並將其傳遞給子級
父母.ts
obj = { value: ''; };
父.html
<child [obj]="obj"></child>
孩子接收對象並更新其上的屬性。
child.ts
@Input() obj: { value: string };
someMethod(): void {
// update obj, which both parent and child reference
this.obj.value = 'CHILD';
}
最終結果:每當父級從屬性中讀取時,它將看到子級設置的值。
編輯:
正如 Michael D 指出的那樣,我選擇傳遞對象而不是字符串,因為傳遞的是對象引用而不是字面值。
您可以使用ViewChild
訪問父組件中的子數據。
演示: Stackblitz
import { Component, Input } from '@angular/core';
@Component({
selector: 'hello',
template: `<h1>Hello {{name}}!</h1>`,
styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent {
@Input() name: string;
secretString: string = "Hi there!";
}
子組件:
將您的子組件放在父組件中並標記它:
<hello #cmp></hello>
使用 ViewChild 訪問組件內部的數據
@ViewChild('cmp', {static: true}) hi;
<p>
This is comming from your child: {{hi.secretString}}
</p>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.