简体   繁体   English

亲子沟通无事件

[英]Parent to child communication without event

I have string parameter in child component that I need to show in my parent component.我在子组件中有字符串参数,需要在父组件中显示。 It should be done when the page is loading.它应该在页面加载时完成。 So, not on click or any other event.所以,不是点击或任何其他事件。

How do you manage to do this?你是如何做到这一点的?

So far I didn't find any answer that would fit my solution.到目前为止,我没有找到任何适合我的解决方案的答案。

So ruling out communication via events, you have the following options:因此,排除通过事件进行通信,您有以下选择:

  1. Communicate via a shared service.通过共享服务进行通信。 This is a common strategy, no example required.这是一种常见的策略,无需示例。

  2. Pass an object from the parent to the child.将对象从父对象传递给子对象。 If the child updates a property on the the object reference, the parent will also see that updated value (albeit without notifications).如果子级更新对象引用上的属性,则父级也会看到更新后的值(尽管没有通知)。

Demo: https://stackblitz.com/edit/angular-h7h5xl演示: https : //stackblitz.com/edit/angular-h7h5xl

The principle:原则:

Parent creates an object and passes it to the child父级创建一个对象并将其传递给子级

parent.ts父母.ts

obj = { value: ''; };

parent.html父.html

<child [obj]="obj"></child>

The child receives the object and updates a property on it.孩子接收对象并更新其上的属性。

child.ts child.ts

@Input() obj: { value: string };

someMethod(): void {
  // update obj, which both parent and child reference
  this.obj.value = 'CHILD';
}

End result: whenever the parent reads from the property, it will see the value that the child has set.最终结果:每当父级从属性中读取时,它将看到子级设置的值。

Edit:编辑:

As Michael D points out, I chose to pass an object through rather than a string because object references are passed around rather than literal values.正如 Michael D 指出的那样,我选择传递对象而不是字符串,因为传递的是对象引用而不是字面值。

You can use ViewChild to access children data in the parent component.您可以使用ViewChild访问父组件中的子数据。

Demo : Stackblitz演示: 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!";
}

Child component :子组件:

Place your child component in the parent and tag it:将您的子组件放在父组件中并标记它:

<hello #cmp></hello>

Use ViewChild to access the data inside you component使用 ViewChild 访问组件内部的数据

@ViewChild('cmp', {static: true}) hi;
<p>
  This is comming from your child: {{hi.secretString}}
</p>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM