I was studying the Create a feature component tutorial on angular.io and then I noticed the @Input
decorator property:
// src/app/hero-detail/hero-detail.component.ts import { Component, OnInit, Input } from '@angular/core'; import { Hero } from '../hero'; @Component({ selector: 'app-hero-detail', templateUrl: './hero-detail.component.html', styleUrls: ['./hero-detail.component.css'] }) export class HeroDetailComponent implements OnInit { @Input() hero: Hero; constructor() { } ngOnInit() { } }
What is @Input()
and what is it used for?
@Input is a decorator to mark a property as an input. @Input is used to define an input property, to achieve component property binding. @Inoput decorator is used to pass data (property binding) from parent to child component. The component property should be annotated with @Input decorator to act as input property.
While Angular inputs/outputs should be used when sharing data to and from child components, ViewChild should be used when trying to utilize properties and methods of the child component directly in the parent component.
@Input defines the input property in the component, which the parent component can set. The @output defines the output property (event), which we raise in the child component using the EventEmitter . The parent listens to these events. Applies to: Angular 2 to the latest edition of i.e. Angular 8.
Input values are optional by default. Your code will fail only when it tries to access properties of inputs that are not actually passed (since those inputs are undefined ).
In this example, hero-detail is a child component, it's meant to be inserted into a parent component which will have the 'hero' data, and that 'hero' data will be passed into the hero-detail component via the hero instance variable marked as an input by the @Input decorator.
Basically the syntax is:
Import the Hero interface from the hero.interface.ts file, this is the definition of the Hero class
import { Hero } from "./hero";
Use an Input decorator to make the following instance variable available to parent components to pass data down.
@Input()
The hero instance variable itself, which is of type Hero, the interface of which was imported above:
hero: Hero;
A parent component would use this hero-detail child component and pass the hero data into it by inserting it into the html template like this:
<hero-detail [hero]="hero"></hero-detail>
Where the parent component has an instance variable named 'hero', which contains the data, and that's passed into the hero-detail component.
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