I'm wondering how angular handle an object shared between a parent and child component.
Let me show you a simple example: ParentComponent
@Component({
selector: 'app-parent',
template: `<app-children [(data)]="message"></app-children>
<div>Parent: {{message}}</div>`,
})
export class ParentComponent implements OnInit {
public message: string;
ngOnInit() {
this.message = 'Original message'
}
}
Children Component
@Component({
selector: 'app-children',
template: `<div>Children: {{data}}</div>
<a (click)="changeMessage('Children message')">Click me!</a>`
})
export class ChildrenComponent {
@Input() public data: string;
changeMessage(message: string) {
this.data = message;
}
}
When I click on the "Click me!" link, i see only the Children message change, but not the parent one. Isn't it the same object?
Passing values from a parent component to a child component is simple; we only have to pass the values as props of the child element. To illustrate this concept, take a look at the following code. This code is equivalent to the zombie selection process performed by the trainers. In this battle, we are sending a Humbug and a Geek to fight.
Thus, we can see there is no way to pass props from a child component to a parent component. However, we can always pass around functions from the parent to child component. The child component can then make use of these functions.
While 'parent' and 'child' alone refer to React component hierarchy. myApp component is a parent for Foo component, and Foo component is a child of myApp component: export default class myApp extends React.Component { state = { foo: true }; render () { return ( <Foo foo= {this.state.foo} /> ); } }
Also, state can be passed down as props to any child component. Let's take a look at how that can be done: Our child component is not aware fo whether the incoming props are state or coming as props from our parent component.
consider you should emit the changed value from child and also your emitter name should be [your bind var name]+'Change'
so it will work:
import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-root',
template: `<app-children [(data)]="message"></app-children>
<div>Parent: {{message}}</div>`,
})
export class AppComponent {
public message: string;
ngOnInit() {
this.message = 'Original message'
}
}
@Component({
selector: 'app-children',
template: `<div>Children: {{data}}</div>
<a (click)="changeMessage('Children message')">Click me!</a>`
})
export class ChildComponent {
@Input() public data: string;
@Output() dataChange= new EventEmitter<string>();
changeMessage(message: string) {
this.data = message;
this.dataChange.emit(this.data);
}
}
check DEMO and creating custom two-way data bindings.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With