组件无法正确呈现

时间:2016-03-24 00:53:04

标签: angular

我创建了一个plunker来显示问题所在。

https://plnkr.co/edit/a7F616WCoKbSGXzlYGsM?p=preview

我有一个我想要在另一个组件中使用的组件,我导入它并将其添加到组件装饰器的指令:[]并且它不会渲染...

组件是line-list.component,它的选择器是gb-line-list,我试图在这个文件app / area-list.component.ts中使用它。

第一页显示了一个区域列表,当点击一个区域时,我想用一个列表显示该区域的详细信息。这就是那些没有渲染的行列表......

区域detail.component.ts

import {Component, Input, OnInit} from 'angular2/core';
import {RouteParams} from 'angular2/router';
import {LineListComponent} from './line-list.component';
import {Area} from './area.interface';
import {LineService} from './lines.service';

@Component({
    selector: '[gb-area-detail]',
    directives: [LineListComponent],
    template: `
        <div *ngIf="area">
            <h2>{{area.name}} area</h2>
            <gb-line-list [areaId]="area.id"></gb-line-list>
        </div>
    `
})
export class AreaDetailComponent implements OnInit {
    private area: Area;

    constructor(
        private _lineService: LineService,
        private _routeParams: RouteParams){}

    ngOnInit() {
        let id = +this._routeParams.get('id');

        this._lineService.getArea(id)
            .then(area => this.area = area);
    }

}

线list.component.ts

import {Component, OnInit, Input} from 'angular2/core';

import {LineService} from './lines.service';
import {Line} from './line.interface';

@Component({
    selector: '[gb-line-list]',
    template: `
        <ul>


          <li *ngFor="#line of lines">{{line.name}}</li>
        </ul>
    `
})
export class LineListComponent implements OnInit {
   @Input() areaId: number;

   private lines: Line[];

   constructor (
       private _lineService: LineService) {}

   getLines() {
       this._lineService.getLines(this.areaId)
        .then(lines => this.lines = lines);
   }

   ngOnInit() {
       this.getLines();
   }
}

1 个答案:

答案 0 :(得分:2)

问题在于您将选择器定义为属性选择器selector: '[gb-line-list]',但是您尝试使用元素选择器<gb-line-list [areaId]="area.id"></gb-line-list>来渲染组件。

您有两种选择:
- 将选择器更改为selector: 'gb-line-list'
- 或者将元素更改为<div gb-line-list [areaId]="area.id"></div>

最后,您可能会受益于Angular Cheat Sheet