2

我真的很困惑,我试图在Angular 4中将数据从一个组件注入到另一个组件,看起来数据通过但不会显示,我将直接进入示例代码:

board.component.ts:

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

@Component({
  selector: 'game-board',
  template: `<card [init]="name"></card>`,
})

export class BoardComponent  {
  name: string = 'this is the card name';
}

Card.component.ts:

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

    @Component({
      selector: 'card',
      template: `<div class="card-container"> 
                    CARD - {{strength}}
                 </div>`,
    })
    export class CardComponent  {
      @Input('init') strength: string;
    }

除了结果是“CARD - 这是卡名”之外,我认为它只是“CARD - ”。

这是元素的样子(chrome dev tools,忽略'CARD -'和''之间的差距):

在此处输入图像描述

所以我看到注入有效并且"this is the card name"通过了,但由于某种原因strength是未定义的。

我究竟做错了什么?

4

1 回答 1

3

确保主要组件在 ngModule 定义的引导属性中定义,并且两个组件都定义为声明。应该看起来像这样:

@NgModule({
  imports:      [ BrowserModule ],
  declarations: [ BoardComponent, CardComponent ],
  bootstrap:    [ BoardComponent ]
})

只有主要组件应该在引导数组和声明数组中定义。

于 2017-03-28T07:09:27.073 回答