【发布时间】:2018-12-10 13:43:55
【问题描述】:
目前我只知道这些方法:
- @输入/@输出 |这是为了让孩子与父母交流,反之亦然
- @ViewChild |这是为了和子组件通信
- @Injectable 服务 |与任何组件共享数据
- rxjs/behaviorsubject |与任何组件共享数据
我还看到了一个@Injectable 组件示例,但我不确定这是否也是共享组件数据的一种方式。
好的,所以我希望上面的文字足够清晰,以便大家能够理解我要去哪里。我需要最有效和最干净的方式来与任何组件共享组件变量和方法,而不必造成大混乱并看到性能下降。
我正在考虑使用以下方式共享数据,但我不确定这在拥有多个组件时是否有效:
家长
import { Component, OnInit, ViewChild, AfterViewInit } from '@angular/core';
import { ChildComponent } from './child/child.component';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.scss']
})
class ParentComponent implements OnInit, AfterViewInit {
public instance: ParentComponent;
@ViewChild(ChildComponent) childComponent;
constructor() {
this.instance = this;
}
doSomethingWithParentMethod(strData: string) {
console.log('parent data: ' + strData);
}
ngOnInit(): void {
}
ngAfterViewInit() {
this.childComponent.doSomethingMethod('pass data to child in string type');
}
}
在父 HTML 文件中:
<app-child [parent]="instance"></app-child>
孩子
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.scss']
})
class ChildComponent {
@Input() parent;
public function doSomethingMethod(strData: string) {
console.log('child data: ' + strData);
}
}
【问题讨论】:
标签: angular typescript components angular6 data-sharing