【问题标题】:Angular2: how can component bind to class?Angular2:组件如何绑定到类?
【发布时间】:2016-05-20 22:56:03
【问题描述】:

我找不到@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;
    }
}

【问题讨论】:

    标签: components angular


    【解决方案1】:

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

    这对所有注释都是一样的。

    例如

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

    这里@Inject()绑定到val

    【讨论】:

    • @Component 是一个装饰器 ;-)
    • 谢谢!在 Dart 中,它们被命名为注解,还有其他注解。
    • 是的,在 TypeScript 中,它有点不同。它不仅仅是元数据,而是一种拦截器......
    • 感谢您的解释。
    • 但是如果我切换两个类的位置为什么会导致错误,例如看到这里stackblitz.com/edit/angular-refder?file=app%2Fapp.component.ts
    猜你喜欢
    • 2017-01-09
    • 2015-07-11
    • 1970-01-01
    • 2016-12-10
    • 1970-01-01
    • 2017-06-19
    • 1970-01-01
    • 1970-01-01
    • 2016-06-08
    相关资源
    最近更新 更多