Raphael Rafatpanah Raphael Rafatpanah - 5 months ago 10
AngularJS Question

In the Angular 2 Quickstart, what is the purpose of the HeroDetailComponent class's @Input statement?

In the multiple compenents section of the Angular 2 Quickstart tutorial, a component is extracted out of the previous AppComponent in order to make it more reusable and easier to test.

Run the live example.

A user can click on a list of

Heroes
and a detailed view will appear below the list.

The components:


  1. AppComponent (List of Heroes)

  2. HeroDetailComponent (Display details once a hero is selected)



Both of which import the Hero class:

export class Hero {
id: number;
name: string;
}


In the AppComponent's template,
hero
is a target property:

<my-hero-detail [hero]="selectedHero"></my-hero-detail>


The
selectedHero
source property is set once a user clicks on a listed hero.

So far, so good.

Now, the problem is that I'm not understanding the purpose of
@Input
in the
HeroDetailComponent
class:

export class HeroDetailComponent {
@Input()
hero: Hero;
}


If
@Input()
is omitted, it seems the
hero
property is never set. How does
@Input()
know where to get the
hero
property from? Why is this statement required and not just automatically called when a directive has a target property?

It is not obvious to me and it seems that I may be missing the bigger picture.

Answer

The input is the counterpart of [hero]= of

<my-hero-detail [hero]="selectedHero"></my-hero-detail>

The line above passes selectedHero of the current component to the @Input() hero:hero of the <my-hero-detail> component which I assume is implemented by HeroDetailComponent (didn't check the link).