Grozz
Grozz

Reputation: 8425

Creating Angular 2 components in markup

How do I create my components in (nested) markup?

<component-name [field]="value"></component-name> doesn't seem to work.

Consider the following example:

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);

Outputs:

Name:

Upvotes: 0

Views: 456

Answers (1)

alexpods
alexpods

Reputation: 48505

You should mark name property of HeroDetail component as "input". For this you can use either @Input decorator or inputs property of @Component decorator. See 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);

Upvotes: 1

Related Questions