I was studying the Create a feature component tutorial on angular.io and then I noticed the @Input
decorator property:
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:
.
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:
.
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
parent.component.ts
@Component({...})
export class ParentComponent {
public hero: Hero = new Hero();
}