AngularJs 2 中 AppComponent 和 @Component 之间有什么联系?

Har*_*eja 5 typescript angular

示例中的文件app.component.ts:https://angular.io/resources/live-examples/toh-1/ts/plnkr.html如下:

import { Component } from '@angular/core';

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

@Component({
  selector: 'my-app',
  template:`
    <h1>{{title}}</h1>
    <h2>{{hero.name}} details!</h2>
    <div><label>id: </label>{{hero.id}}</div>
    <div>
      <label>name: </label>
      <input [(ngModel)]="hero.name" placeholder="name">
    </div>
    `
})
export class AppComponent {
  title = 'Tour of Heroes';
  hero: Hero = {
    id: 1,
    name: 'Windstorm'
  };
}
Run Code Online (Sandbox Code Playgroud)

现在,我们在AppComponent中设置值title,它会显示在@Component的模板中。那么,想知道这怎么可能吗?

Gün*_*uer 3

@Component()是一个装饰器,应用于直接跟随该装饰器的类、成员或变量。因此,因为@Component()装饰器紧接在class AppComponent()它应用于此类之前。

中的表达式在template: '...'它们所应用的类的范围内进行计算。title因此指的是该title字段AppComponent