Search code examples
angularweb-component

Passing a value to a child component Angular2


I'm trying to pass a value from a parent component to a child component I tried this:

This is my parent component:

import {Component, View, NgFor} from 'angular2/angular2';

import {DisplayCard} from '../display-card/display-card';

@Component({
  selector: 'display'
})
@View({
  templateUrl: './components/display/display.html',
  directives: [DisplayCard, NgFor]
})
export class Display {
  displays: Array<any>;

  constructor(){
    this.displays = [
      {name: "Lobby", appName: "Animal App", Source: 3},
      {name: "Wall", appName: "Idk App", Source: 3},
      {name: "Other Wall", appName: "Monkey App", Source: 3},
      {name: "Lobby Kiosk", appName: "Car App", Source: 3},
      {name: "Another Brick in the Wall", appName: "Pink Floyd App", Source: 3},
    ]
  }
}

Parent component HTML:

<div class="col-md-3" *ng-for="#display of displays">
    <display-card name="{{display.name}}"></display-card>
</div>

Child component:

import {Component, View} from 'angular2/angular2';

@Component({
  selector: 'display-card'
})

@View({
  templateUrl: './components/display-card/display-card.html'
})

export class DisplayCard{
  name: string;
}

Child HTML:

<div class="display-card">
    <div class="display-card-header">

    </div>
  <div class="display-card-body">
    <h1 class="display-card-title">{{name}}</h1>
    <h4 class="display-card-subtitle"></h4>
  </div>
</div>

I added the name property to the child component since this is the error I'm getting when I try this out:

EXCEPTION: Can't bind to 'name' since it isn't a known property of the '<display-card>' element and there are no matching directives with a corresponding property

Is this even possible with components?


Solution

  • You need to specify the properties on your Component declaration :

    @Component({
      selector: 'display-card',
      properties: ['name']
    })