Search code examples
angularangular2-templateangular2-directives

Can't bind to custom input of component - Angular2


I'm doing an online course on Angular2 but I've run into a problem with getting my custom input to work. I have a simple spinner component which I wish to show only if it's visible input is set to true, but when I run this in the browser I get a can't bind error telling me it is not a native property.

Here's a quick few snippets of what I have:

Spinner Component

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; 
}

Posts Component

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;
    }
}

Solution

  • It looks like you haven't told PostsComponent about the 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;
        }
    }