@Input()在Angular中有什么用? [英] What is @Input() used for in Angular?
问题描述
我正在研究创建要素组件关于angular.io的教程,然后我注意到了 @Input
装饰器属性:
I was studying the Create a feature component tutorial on angular.io and then I noticed the @Input
decorator property:
// 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() { }
}
什么是 @Input()
,它的作用是什么?
What is @Input()
and what is it used for?
推荐答案
在此示例中,hero-detail是子组件,它应插入具有英雄"数据的父组件中,并且该英雄的数据将通过由@Input装饰器标记为输入的hero实例变量传递到hero-detail组件中.
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.
基本上语法是:
从hero.interface.ts文件中导入Hero接口,这是Hero类的定义
Import the Hero interface from the hero.interface.ts file, this is the definition of the Hero class
import { Hero } from "./hero";
使用Input装饰器使父组件可以使用以下实例变量来向下传递数据.
Use an Input decorator to make the following instance variable available to parent components to pass data down.
@Input()
hero实例变量本身,类型为Hero,其接口在上面导入:
The hero instance variable itself, which is of type Hero, the interface of which was imported above:
hero: Hero;
父组件将使用此英雄细节子组件,并将英雄数据通过将其插入html模板中来传递给它,如下所示:
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>
父组件的实例变量名为"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()在Angular中有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!