angular2学习笔记(3)

来源:互联网 发布:mac磁盘怎么看空间 编辑:程序博客网 时间:2024/06/05 15:59

 

Click事件:

笔记2的基础实现点击事件

先看一下app.component.ts最终的代码:


import {Component}from '@angular/core';

 

interface Hero {

id: number;

name: string;

}

 

@Component({

selector: 'my-app',

template: `

<h1>{{title}}</h1>

<div *ngIf="selectedHero">

<h2>{{selectedHero.name}} </h2>

<div><label>id: </label>{{selectedHero.id}}</div>

<div>

<label>name: </label>

<div><input [(ngModel)]="selectedHero.name" placeholder="name"></div>

</div>

</div>

<h2>英雄列表</h2>

<ul class="heroes">

<li *ngFor="#hero of heroes"

[class.selected]="hero === selectedHero"

(click)="onSelect(hero)">

<span class="badge">{{hero.id}}</span> {{hero.name}}

</li>

</ul>

`

,

styles:[`

.heroes {list-style-type: none; margin-left: 1em; padding: 0; width: 10em;}

.heroes li { cursor: pointer; position: relative; left: 0; transition: all 0.2s ease; }

.heroes li:hover {color: #369; background-color: #EEE; left: .2em;}

.heroes .badge {

font-size: small;

color: white;

padding: 0.1em 0.7em;

background-color: #369;

line-height: 1em;

position: relative;

left: -1px;

top: -1px;

}

.selected { background-color: #EEE; color: #369; }

`]

})

export class AppComponent {

public title ='英雄联盟';

hero: Hero = {

id: 1,

name: '法外狂徒'

};

public heroes = HEROES;

public selectedHero: Hero;

onSelect(hero: Hero) { this.selectedHero = hero; }

}

 

var HEROES: Hero[] = [

{ "id":11,"name":"奥巴马" },

{ "id":12,"name":"希维尔" },

{ "id":13,"name":"蒙多" },

{ "id":14,"name":"拉克丝" },

{ "id":15,"name":"波比" },

{ "id":16,"name":"提莫" },

{ "id":17,"name":"卡萨丁" },

{ "id":18,"name":"布兰德" },

{ "id":19,"name":"阿卡丽" },

{ "id":20,"name":"卡尔玛" }

];

 

上面代码主要是点击事件需在html元素上添加关键代码


(click)="onSelect(hero)">


onSelect是函数名称,传入了一个参数heroonSelect函数定义在AppComponent 类中,代码如下


onSelect(hero: Hero) { this.selectedHero = hero; }


在运行过程中,selectedHero第一次为空,我们需要判断一下selectedHero是否为null判断一个变量是否为空可以使用*ngIf

在点击事件后,有时候需要更新一下样式,以表示当前选中项,示例代码:


[class.selected]="hero === selectedHero"


[class.selected]的取值是truefalse, true表示样式生效。 模板中的html元素的属性绑定用[ ]


运行项目效果如下:


 

0 0