所有这些答案都使事情变得过于复杂。对于直接的父 -> 子或子 -> 父通信,您可以简单地使用依赖注入,当组件被实例化时,您可能经常使用相同的技术在构造函数中注入其他 Angular 类。
假设你有一些父组件
export class ParentComponent {
someString: string;
constructor( ) {}
someMethod() {
return someVal : any;
}
private somePrivateMethod() { return 'cant touch this' }
}
在它的任何子组件中,您可以将该父组件的实例作为参数注入到 childcomponents 构造函数中。您只需要像导入其他类一样导入它。
import { ParentComponent } from './wherever/parent/is/'
export class ChildComponent {
constructor(private parent:ParentComponent) { }
ngOnInit() {
let abc = this.parent.someMethod(); // works bc method is public
let nope = this.parent.somePrivateMethod(); // will throw a compile error
}
}
现在,子组件可以使用 this.parent.whatever 访问父组件的任何公共方法或属性。
为了与父组件进行通信,您可以在父组件中创建一个对象来存储 ChildComponent 的实例。同样,将 ChildComponent 导入 ParentComponent 文件。
import { ChildComponent } from './wherever/child/is'
export class ParentComponent {
someString: string;
someNum: number;
arrayOfChildren: ChildComponent[] = [];
constructor( ) {}
someMethod() {
return someVal : any;
}
addChild( child: ChildComponent ) {
this.arrayOfChildren.push(child);
}
}
然后在父组件中添加一些方法,将其子组件的实例添加到数组中(使用映射可能更好,但我现在保持简单)。
然后在子级中,您只需在添加子级的父级中调用该方法
export class ChildComponent {
constructor(private parent:ParentComponent) { }
ngOnInit() {
this.parent.addChild(this);
}
}
现在您的孩子可以通过 this.parent 访问父母的公共属性,您的父母可以通过 this.arrayOfChildren[0] 访问其孩子的公共属性。反应式编程很棒,但它非常适合需要在不直接分层相关的指令/组件之间进行通信。当您有直接关系时,有更简单的选择。
注意:我选择数组的唯一原因是因为父母通常有很多后代。你没有理由不能只创建一个名为
的属性
myChild: ChildComponent;
并将孩子直接存储到那里。