无法绑定到组件的自定义输入 - Angular2

时间:2016-08-08 17:46:37

标签: angular angular2-template angular2-directives

我正在进行Angular2的在线课程,但是我遇到了让自定义输入工作的问题。我有一个简单的微调器组件,我希望只有当它的可见输入设置为true时才会显示,但是当我在浏览器中运行它时,我得到一个无法绑定错误,告诉我它不是本机属性。

以下是我所拥有的几个片段:

微调器组件

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

@Component({
    selector: 'spinner',
    template: `
        <i *ngIf="visible" class="fa fa-spinner fa-spin fa-3x"></i>
    `
})
export class SpinnerComponent { 
    @Input() visible = true; 
}

帖子组件

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

import {PostsService} from './posts.service';
import {SpinnerComponent} from './spinner.component.ts'

@Component({
    selector: '<posts></posts>',
    template: `
        <h1>Posts</h1>
        <spinner [visible]="postsLoading"></spinner>
        <div class="row">
            <ul class="list-group col-sm-6">
                <li *ngFor="#post of posts" class="list-group-item">
                    {{ post.body }}
                </li>
            </ul>
        </div>
    `,
    providers: [HTTP_PROVIDERS, PostsService]
})

export class PostsComponent implements OnInit { 

    postsLoading;
    posts = [];

    constructor(private _posts_service : PostsService) {
    }

    ngOnInit() {
        this._posts_service.getPosts()
            .subscribe(posts => this.posts = posts);

        this.postsLoading = false;
    }
}

2 个答案:

答案 0 :(得分:1)

看起来你没有告诉PostsComponent有关SpinnerComponent

的信息
import {Component, OnInit} from 'angular2/core';
import {HTTP_PROVIDERS} from 'angular2/http';

import {PostsService} from './posts.service';
import {SpinnerComponent} from './spinner.component.ts'

@Component({
    selector: 'posts',
    template: `
        <h1>Posts</h1>
        <spinner [visible]="postsLoading"></spinner>
        <div class="row">
            <ul class="list-group col-sm-6">
                <li *ngFor="#post of posts" class="list-group-item">
                    {{ post.body }}
                </li>
            </ul>
        </div>
    `,
    providers: [HTTP_PROVIDERS, PostsService], 
    directives: [SpinnerComponent]
})

export class PostsComponent implements OnInit { 

    postsLoading;
    posts = [];

    constructor(private _posts_service : PostsService) {
    }

    ngOnInit() {
        this._posts_service.getPosts()
            .subscribe(posts => this.posts = posts);

        this.postsLoading = false;
    }
}

答案 1 :(得分:0)

  • 选择器应该是CSS选择器
  • 指令需要列出您在模板中使用的指令
@Component({
    selector: 'posts',
    directives: [SpinnerComponent],
    template: `
      ....
    `,
    providers: [HTTP_PROVIDERS, PostsService]
})