在标记中创建Angular 2组件

时间:2015-11-04 08:47:54

标签: typescript angular

如何在(嵌套)标记中创建我的组件?

<component-name [field]="value"></component-name>似乎不起作用。

考虑以下示例:

import {bootstrap, Component, FORM_DIRECTIVES, CORE_DIRECTIVES} from 'angular2/angular2';

@Component({
  selector: "hero-detail",
  directives: [FORM_DIRECTIVES, CORE_DIRECTIVES],
  template: `Name: {{name}}`
})
class HeroDetail {
  public name: string;
}

@Component({
  selector: 'my-app',
  directives: [FORM_DIRECTIVES, CORE_DIRECTIVES, HeroDetail],
  template:`
    <h1>Heroes</h1>
    <hero-detail [name]="name"></hero-detail>
  `
})
class AppComponent { 
    public name: string = "Funky name";
}

bootstrap(AppComponent);

输出:

Name:

1 个答案:

答案 0 :(得分:1)

您应将name组件的HeroDetail属性标记为&#34;输入&#34;。为此,您可以使用@Input装饰器的inputs装饰器或@Component属性。请参阅this plunker

import {bootstrap, Component, Input} from 'angular2/angular2';

@Component({
  selector: "hero-detail",
  template: `Name: {{name}}`,
  // inputs: ['name'] <-- you can use "inputs" property in @Component
})
class HeroDetail {
  @Input() name: string; // or @Input property decorator
}

@Component({
  selector: 'my-app',
  directives: [HeroDetail],
  template:`
    <h1>Heroes</h1>
    <hero-detail [name]="name"></hero-detail>
  `
})
class AppComponent { 
    public name: string = "Funky name";
}

bootstrap(AppComponent);