简体   繁体   中英

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

The principle:

Parent creates an object and passes it to the child

parent.ts

obj = { value: ''; };

parent.html

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

The child receives the object and updates a property on it.

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.

You can use ViewChild to access children data in the parent component.

Demo : 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('cmp', {static: true}) hi;
<p>
  This is comming from your child: {{hi.secretString}}
</p>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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