Angular2笔记2-多个组件

每个组件就是@Component+class + html标签, 组件内部的交互 和 多个组件之间的通信都用了Angular2自己的语法
满满都是套路啊 记录一下

UI交互

用#newtitle保持引用, (click)=”fun()”绑定事件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
//<input name="title" #newtitle>用#newtitle声明引用
//<button (click)="addArticle(newtitle, newlink)" 事件相应传参
@Component({
selector: 'reddit',
template: `
<form class="ui large form segment">
<h3 class="ui header">Add a Link</h3>
<div class="field">
<label for="title">Title:</label>
<input name="title" #newtitle>
</div>
<div class="field">
<label for="link">Link:</label>
<input name="link" #newlink>
</div>
<button (click)="addArticle(newtitle, newlink)" class="ui positive right floated button">
Submit link
</button>
</form> `
})
class RedditApp {
constructor() {}
//相应事件, 类型是HTMLInputElement, 取值靠.value
addArticle(title: HTMLInputElement, link: HTMLInputElement): void {
console.log(`Adding article title: ${title.value} and link: ${link.value}`);
}
}
bootstrap(RedditApp);

多个组件

RedditApp是最顶级的组件, ArticleComponent是他的子组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
//同一页面的第二个组件
@Component({
selector: 'reddit-article',
host: {
class: 'row'//相当于在html里写 class="roe"
},
template: `
<div class="four wide column center aligned votes">
<div class="ui statistic">
<div class="value"> {{ votes }}</div>
<div class="label">Points</div>
</div>
</div>
<div class="twelve wide column">
<a class="ui large header" href="{{ link }}"> {{ title }}</a>
<ul class="ui big horizontal list voters">
<li class="item">
<a href (click)="voteUp()">
<i class="arrow up icon"></i> upvote
</a>
</li>
<li class="item">
<a href (click)="voteDown()">
<i class="arrow down icon"></i>
downvote
</a>
</li>
</ul>
</div>`
})
class ArticleComponent {
votes:number;//对应组件里的变量{{ votes }}
title:string;
link:string;
constructor() {
this.votes = 10;
this.title = 'Angular 2';
this.link = 'http://angular.io';
}
voteUp() {
this.votes += 1;
return false;//阻止默认行为(因为是在<a>里)
}
voteDown() {
this.votes -= 1;
return false;
}
}
//并没有自己去渲染, 而是靠其他@Component的directives参数(要先于其他组件声明)
////////////////////////////////////////////////////////////////
//directives里的其他组件要先于此组件声明, 不然就是undefined
@Component({
selector: 'reddit',
directives: [ArticleComponent],//模版末尾集成另一个组件<reddit-article>, 对应类ArticleComponent
template: `
<form>...</form>
<div class="ui grid posts">
<reddit-article></reddit-article>
</div>`
})
class RedditApp {
//...
}
bootstrap(RedditApp);