angular2學習筆記之事件和多組件

組件免不了和用戶交互,而交互中使用最頻繁的莫過於點擊事件的交互。angular2-demo
點擊訪問小莫的githubcss

1、 點擊事件

代碼解讀html

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 就是引用的另外一個組件,這個組件源自於上一篇博客基本組件git

<div>
    <basic></basic>
    <button class="btn btn-success" (click)="showMsg()">點擊事件</button>
</div>

2、鍵盤按下事件

1. KeyupEvent.ts

初始化一個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 + ' | ';
    }
}

2. KeyupEvent.html

當鍵盤按下的時候調用onKey方法數組

<div>
    <input #box (keyup)="onKey(box.value)" title="">
    <p>{{values}}</p>
</div>

3、 enter事件和失焦事件

1. EnterBlurEvent.ts

定義一個heroes數組並給幾個初始值,添加英雄方法能夠增長一個新的英雄到heroesangular2

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方法,而後循環輸出heroesui

<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>
相關文章
相關標籤/搜索