2

组件免不了和用户交互,而交互中使用最频繁的莫过于点击事件的交互。angular2-demo
点击访问小莫的github

一、 点击事件

代码解读

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

当键盘按下的时候调用onKey方法

<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>

奋进的小莫
996 声望101 粉丝

[链接]