简体   繁体   English

将值传递给子组件Angular2

[英]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: 父组件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: 子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: 我将name属性添加到子组件中,因为这是我尝试时遇到的错误:

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? 使用组件甚至有可能吗?

You need to specify the properties on your Component declaration : 您需要在Component声明中指定properties

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM