I was studying the Create a feature component tutorial on angular.io and then I noticed the @Input
decorator property:
Simply, by using the input
decorator you are telling angular that a variable named hero
will take Hero
object as input from 'HeroDetailComponent' and will be able to pass this Hero
object to any of its child component. This is called Input Binding
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.
@Input() hero
means that hero
is a variable that is being passed on to this component from it's parent.e.g
<hero-detail [hero]="(object of hero)"> </hero-detail>
Here I am passing hero object to hero
detail component from it's parent component.
1. @Input
creates a attribute on the components selector
Using the @Input
selector creates an attribute on the selector. So using @Input() hero_name: string
in a child.component.ts
would create an attribute called hero_name
.
In parent.component.html
this looks something like: <app-child hero_name='Batman'></app-child>
.
In child.component.ts
you would be able to access this value using this.hero_name
.
2. use different names for @Input
@Input() hero_name: string
is actually a shorthand for @Input('hero_name') hero_name: string
. You could assign a different name if that is more convenient.
E.g.: @Input('hero_name') name: string
.
In parent.component.html
this looks something like: <app-child hero_name='Batman'></app-child>
.
In child.component.ts
you would be able to access this value using this.name
.
3. combine it with property binding
If you combine this with property binding you can now get objects or whatever from your parent.component.ts
and pass it to your child-component.ts
.
Example:
child.component.ts
@Component({...})
export class ChildComponent {
@Input('selected_hero') superhero: Hero;
public some_function() {
console.log(this.superhero);
}
}
parent.component.html
<app-child [selected_hero]='hero'></app-child>
parent.component.ts
@Component({...})
export class ParentComponent {
public hero: Hero = new Hero();
}