Implement this pattern with the @Input() and @Output() decorators.
Consider the following hierarchy:
<parent-component>
<child-component></child-component>
</parent-component>
give a child component a way to communicate with its parent component.
@Input() lets a parent component update data in the child component. Conversely, @Output() lets the child send data to a parent component.
Sending data to a child component
The
@Input()
decorator in a child component or directive signifies that the property can receive its value from its parent component.To use @Input()
, you must configure the parent and child.
Configuring the child component
To use the @Input()
decorator in a child component class, first import Input
and then decorate the property with @Input()
, as in the following example.
import { Component, Input } from '@angular/core'; // First, import Input
export class ItemComponent {
@Input() item = ''; // decorate the property with @Input()
}
In this case, @Input()
decorates the property item
, which has a type of string
, however, @Input()
properties can have any type, such as number
, string
, boolean
, or object
. The value for item
comes from the parent component.
Next, in the child component template, add the following:
<p>
Today's item: {{item}}
</p>
No comments:
Post a Comment