Looking at the multiple components part of the Angular 2 Quickstart tutorial, we see how a component is separated from the AppComponent to enhance reusability and testing convenience.
You can try out the example live demo here.
In this scenario, users are able to select a Hero from a list and view its detailed information below the list.
The key components involved are:
- AppComponent (List of Heroes)
- HeroDetailComponent (Displays hero details when selected)
Both components make use of the Hero class:
export class Hero {
id: number;
name: string;
}
Within the template of the AppComponent, the hero
serves as a target property:
<my-hero-detail [hero]="selectedHero"></my-hero-detail>
The source property for selectedHero
gets assigned when a user clicks on a listed hero.
Everything seems fine so far.
However, I'm facing some confusion with the purpose of using @Input
in the HeroDetailComponent
class:
export class HeroDetailComponent {
@Input()
hero: Hero;
}
If @Input()
is not included, it appears that the hero
property won't be initialized. How does @Input()
determine where to fetch the value of the hero
property from? Why is this declaration necessary instead of being automatically invoked when a directive has a target property?
This aspect is not entirely clear to me, and it feels like there might be more to understand beyond what meets the eye.