3 common methods that we can use to share data between Angular components.
- Sharing Data via Input
- Sharing Data via Output and EventEmitter
- Sharing Data with a Service
When you declare a variable in the child component with the @Input() decorator, it allows that variable to be “received” from the parent component template.
import { Component } from "@angular/core"
@Component({
selector: "app-parent",
template: "parent.component.html",
styleUrls: ["./parent.component.css"],
})
export class ParentComponent {
Message = "Parent to Child"
constructor() {}
}
See that the way a prop is passed from the parent.component.html is using the syntax
[prop]="prop"
To compare with React it would be like
<ChildComp firstName={firstName}>
<app-child [Message]="Message"></app-child>
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-child',
template: './child.component.html,
styleUrls: ['./child.component.css']
})
export class ChildComponent {
@Input() Message: string;
constructor() { }
}
<h1>
Message from Parent : {{Message}}
<h1></h1>
</h1>