組件免不了和用戶交互,而交互中使用最頻繁的莫過於點擊事件的交互。angular2-demo
css
代碼解讀html
import {Component} from '@angular/core'; import {BasicComponent} from './../basic/Basic'; @Component({ selector:'click-event', styles:[require('./ClickEvent.scss')], template: require('./ClickEvent.html'), directives:[BasicComponent] //須要引用的組件 }) export class ClickEventComponent{ showMsg():void{ console.log('己經觸發點擊事件'); alert('己經觸發點擊事件'); } }
basic 就是引用的另外一個組件,這個組件源自於上一篇博客基本組件git
<div> <basic></basic> <button class="btn btn-success" (click)="showMsg()">點擊事件</button> </div>
初始化一個values
爲空字符串,而後當用戶按下鍵盤的時候把值拼給values
,而且以|
隔開github
import { Component } from '@angular/core'; @Component({ selector:'keyup-event', template: require('./KeyupEvent.html'), styles:[require('./KeyupEvent.scss')] }) export class KeyupEventComponent { values:string = ''; onKey(value:any):void { this.values += value + ' | '; } }
當鍵盤按下的時候調用onKey
方法數組
<div> <input #box (keyup)="onKey(box.value)" title=""> <p>{{values}}</p> </div>
定義一個heroes
數組並給幾個初始值,添加英雄方法能夠增長一個新的英雄到heroes
中angular2
import { Component } from '@angular/core'; @Component({ selector:'enter-blur-event', template: require('./EnterBlurEvent.html'), styles:[require('./EnterBlurEvent.scss')] }) export class EnterBlurEventComponent { heroes = ['Windstorm', 'Bombasto', 'Magneta', 'Tornado']; addHero(newHero: string) { if (newHero) { this.heroes.push(newHero); } } }
當用戶按enter
或者Add
或者blur
失去焦點且不爲空的時候調用newHero
方法,而後循環輸出heroes
ui
<input #newHero (keyup.enter)="addHero(newHero.value)" (blur)="addHero(newHero.value); newHero.value='' "> <button (click)=addHero(newHero.value) class="btn btn-success">Add</button> <ul><li *ngFor="let hero of heroes">{{hero}}</li></ul>