Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2: how can component bind to class?

I can't find the obvious evidence that how a @Component() binds to a class. How can it know component binds with class RedditArticle instead of class Article? After switching the position of the two class, it is messed up. Does that mean the class we need to bind should followed by the corresponding component?

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;
    }
}
like image 218
Ng2-Fun Avatar asked Apr 24 '26 06:04

Ng2-Fun


1 Answers

The @Component() decorator applies directly to the class that follows the annotation.

This is the same for all annotations.

For example

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

Here @Inject() is bound to val

like image 103
Günter Zöchbauer Avatar answered Apr 28 '26 16:04

Günter Zöchbauer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!