![](/img/trans.png)
[英]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.