下午的时候把Angular官网的英雄之旅自己跑了一遍,在这个过程里面看到这里我就有点没弄明白 @input()到底是干嘛用的
// 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() { }
}
之后去搜了一些博客,然后就顺藤摸瓜在stack overflow里面找到了一个个人觉得比较通俗易懂的解释:
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.