Angular2:组件如何绑定到类?

时间:2016-02-10 14:23:59

标签: components angular

我找不到明显的证据表明@Component()如何与一个类绑定。 如何知道组件与类RedditArticle而不是类Article绑定?切换两个班级的位置后,它搞砸了。这是否意味着我们需要绑定的类应该跟着相应的组件?

import { bootstrap } from "angular2/platform/browser";
import { Component } from "angular2/core";

@Component({
    selector: 'reddit-article',
    template: `
        <div class="row">
            <div class="col-md-3"></div>
                <div>Points: {{article.votes}}</div>
            <div class="col-md-9"></div>
                <!--<div class="row">-->
                    Title: {{article.title}}
                    Link: {{article.link}}
                    <button (click)="voteUp()">upvote</button>
                    <button (click)="voteDown()">downvote</button>
                <!--</div>-->
        </div>
    `
})

class RedditArticle {

    article: Article;

    constructor() {
        this.article = new Article('angular2', 'google.com', 0);
    }

    voteUp() {
        this.article.votes++;
    }

    voteDown() {
        this.article.votes--;
    }
}

class Article {
    title: string;
    link: string;
    votes: number;

    constructor(title: string, link: string, votes: number) {
        this.title = title;
        this.link = link;
        this.votes = votes;
    }
}

1 个答案:

答案 0 :(得分:1)

@Component()装饰器直接应用于注释后面的类。

所有注释都是一样的。

例如

constructor(@Inject('xxx') private val:string, private zone:NgZone) {}

此处@Inject()绑定到val