什么是@Input()用于?

5tk*_*tka 37 typescript angular

我决定学习Angular 4并按照https://angular.io/tutorial/toh-pt3上的教程进行操作.但是,问题又出现了.这是什么

@Input () hero: Hero; 
Run Code Online (Sandbox Code Playgroud)

它是为了什么?它有什么作用?这是什么意思?

这是代码.英雄details.component.ts

import { Component, Input } from '@angular/core';
import { Hero } from "./hero";


@Component({
 selector: 'hero-detail',
 templateUrl: './hero-detail.component.html'
})
export class HeroDetailComponent {
 @Input() hero: Hero;
}
Run Code Online (Sandbox Code Playgroud)

下面是对文件的另一个代码app.components.ts,app.components.html,hero-details.components.html

如果有人可以,请解释一下

Ste*_*ith 29

在这个例子中,hero-detail是一个子组件,它意味着插入到具有'hero'数据的父组件中,并且'hero'数据将通过hero实例变量传递到hero-detail组件由@Input装饰器标记为输入.

基本上语法是:

从hero.interface.ts文件导入Hero接口,这是Hero类的定义

import { Hero } from "./hero";
Run Code Online (Sandbox Code Playgroud)

使用输入装饰器使以下实例变量可供父组件使用以传递数据.

@Input()
Run Code Online (Sandbox Code Playgroud)

英雄实例变量本身,其类型为Hero,其界面在上面导入:

hero: Hero;
Run Code Online (Sandbox Code Playgroud)

父组件将使用此英雄详细子组件,并通过将英雄数据插入到html模板中将其传递到其中,如下所示:

<hero-detail [hero]="hero"></hero-detail>
Run Code Online (Sandbox Code Playgroud)

父组件具有名为"hero"的实例变量,其中包含数据,并且传递给hero-detail组件.


Ali*_*asi 13

@Input() hero表示该hero变量是从其父级传递到此组件的变量。例如

<hero-detail [hero]="(object of hero)"> </hero-detail>
Run Code Online (Sandbox Code Playgroud)

在这里,我将hero对象hero从其父组件传递到detail组件。


RMo*_*RMo 8

1.@Input在组件选择器上创建一个属性

使用@Input选择器在选择器上创建一个属性。因此,@Input() hero_name: string在 a 中使用child.component.ts会创建一个名为hero_name.

parent.component.html这看起来像:<app-child hero_name='Batman'></app-child>

child.component.ts您将能够访问使用此值this.hero_name

2.为@Input使用不同的名称

@Input() hero_name: string实际上是 的简写@Input('hero_name') hero_name: string。如果更方便,您可以指定不同的名称。

例如:@Input('hero_name') name: string

parent.component.html这看起来像:<app-child hero_name='Batman'></app-child>

child.component.ts您将能够访问使用此值this.name

3.结合属性绑定

如果您将它与属性绑定结合起来,您现在可以从您的对象中获取对象或任何内容parent.component.ts并将其传递给您的child-component.ts.

例子:

子组件.ts

@Component({...})
export class ChildComponent {
  @Input('selected_hero') superhero: Hero;
  
  public some_function() {
    console.log(this.superhero);
  }
}
Run Code Online (Sandbox Code Playgroud)

父组件.html

<app-child [selected_hero]='hero'></app-child>
Run Code Online (Sandbox Code Playgroud)

父组件.ts

@Component({...})
export class ParentComponent {
  public hero: Hero = new Hero();
}
Run Code Online (Sandbox Code Playgroud)

  • 我找到了关于幕后发生的事情的最佳解释,以及构建数据如何从父组件传递到子组件的绝佳方法。这应该被接受的答案⭐ (2认同)

Kar*_*sai 7

简单地说,通过input关键字告诉您angular变量hero将把Hero对象作为'HeroDetailComponent'的输入,并将该Hero对象传递给它的任何子组件。这称为输入绑定

  • 我认为`@Input`不是一个关键字,而是一个装饰器。 (4认同)