无法在angular2中将数据从一个组件传递到另一个组件

时间:2016-06-18 08:22:40

标签: javascript typescript angular angular2-template

这是非常基本的设置,我正在尝试创建一个简单的可重用数据表组件。但它不起作用。

data_table.component.ts:

import { Component, Input } from '@angular/core';
import { CORE_DIRECTIVES } from '@angular/common';
import {Router, RouteConfig, RouterLink, RouterOutlet, ROUTER_PROVIDERS, ROUTER_DIRECTIVES} from '@angular/router-deprecated';
import {TAB_DIRECTIVES} from 'ng2-bootstrap';
@Component({
    selector: 'data_table',
    templateUrl: './data_table/data_table.html',
    directives: [RouterLink, RouterOutlet, ROUTER_DIRECTIVES, TAB_DIRECTIVES],
    providers: [ROUTER_PROVIDERS]
})
export class DataTableComponent {
    @Input()
    rows: Array<any>;
}

data_table.html:

<table>
    <thead>
        <tr>
            <td>sr</td>
            <td>name</td>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor="let row in rows">
            <td>{{row.sr}}</td>
            <td>{{row.name}}</td>
        </tr>
    </tbody>
</table>

employee.component.ts:

import { Component} from '@angular/core';
import { CORE_DIRECTIVES } from '@angular/common';
import {Router, RouteConfig, RouterLink, RouterOutlet, ROUTER_PROVIDERS, ROUTER_DIRECTIVES} from '@angular/router-deprecated';
import {DataTableComponent} from '../../data_table/data_table.component';

const Emps: Array < any > = [{
    sr: 1,
    name: 'saurabh'
}, {
    sr: 2,
    name: 'arun'
}];

@Component({
    selector: 'employee',
    templateUrl: './app/employee/employee.html',
    directives: [DataTableComponent, RouterLink, RouterOutlet, ROUTER_DIRECTIVES],
    providers: [ROUTER_PROVIDERS]
})

export class EmployeeComponent {
    emps = Emps;
}

employee.html:

<div>
   <data-table [rows]="emps"></data-table> 
</div>

我在控制台中没有任何错误,但是没有填充行。

1 个答案:

答案 0 :(得分:1)

我觉得你的代码中有很少的拼写错误。

您的DataTableComponent错误selector,在您的模板中,您需要在for循环语句中使用of运算符,而不是in

因此,请尝试更改以下行:

@Component({
    selector: 'data-table', <== '_' => '-'

<tr *ngFor="let row of rows"> <==  'in' => `of'