angular2学习笔记(2)

来源:互联网 发布:servlet ajax json 编辑:程序博客网 时间:2024/06/05 17:00

列表显示:


列表显示需要用到ngFor,在 app.component.ts中定义一个数组,数组定义在文件末尾,代码如下:


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":"卡尔玛" }

];

 

上面的代码是定义了一个名称为HEROES的数组,类型是Hero

然后赋值给AppComponent中的属性heroes。


public heroes = HEROES;


使用ngFor指令循环取出heroes的值,template中的代码如下:


<h2>英雄列表</h2>

<ul class="heroes">

<li *ngFor=" let hero of heroes "> <span class="badge">

{{hero.id}}</span>

{{hero.name}}</li>

</ul>


上面使用了class="badge"样式,我们需要在AppComponenttemplate属性后面添加style属性来定义样式的内容。代码如下:


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

`]


至此 循环遍历一个数组基本已实现。app.component.ts中的完整代码如下:


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

 

interface Hero {

id: number;

name: string;

}

 

@Component({

selector: 'my-app',

template: `

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

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

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

<div>

<label>name: </label>

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

</div>

 

<h2>英雄列表</h2>

<ul class="heroes">

<li *ngFor=" let hero of heroes "> <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;

}

 

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":"卡尔玛" }

];

 

 

 

 


0 0
原创粉丝点击