组件免不了和用户交互,而交互中使用最频繁的莫过于点击事件的交互。angular2-demo
一、 点击事件
1. ClickEvent.ts
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('己经触发点击事件'); } }
2. ClickEvent.html
basic 就是引用的另一个组件,这个组件源自于上一篇博客基本组件
<div> <basic></basic> <button class="btn btn-success" (click)="showMsg()">点击事件</button> </div>
二、键盘按下事件
1. KeyupEvent.ts
初始化一个values
为空字符串,然后当用户按下键盘的时候把值拼给values
,并且以|
隔开
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 + ' | '; } }
2. KeyupEvent.html
<div> <input #Box (keyup)="onKey(Box.value)" title=""> <p>{{values}}</p> </div>
三、 enter事件和失焦事件
1. EnterBlurEvent.ts
定义一个heroes
数组并给几个初始值,添加英雄方法可以增加一个新的英雄到heroes
中
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); } } }
2. EnterBlurEvent.html
当用户按enter
或者Add
或者blur
失去焦点且不为空的时候调用newHero
方法,然后循环输出heroes
<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>原文链接:https://www.f2er.com/angularjs/149283.html