前言
我们已经制作出了英雄编辑器,那么我们今天讲这个英雄榜做出来,今天我们主要将css样式添加进去,并且尝试学习复写器的运用,以及隐藏我们的空白处和click事件处理器的使用。
结果展示
我们开始制作此过程
- 首先我们需要和上次一样添加一个类(mock-heroes.ts)文件,在此定义包含10个英雄的数组:
//在src/ap下建立:
import { Hero } from './hero';
export const HEROES : Hero[]=[
{id:11,name: 'Mr.Nice'},
{id:13,name: 'Bombasto'},
{id:14,name: 'Celeritas'},
{id:15,name: 'Magneta'},
{id:16,name: 'RubberMan'},
{id:17,name: 'Dynamic'},
{id:18,name: 'Dr IQ'},
{id:19,name: 'Magma'},
{id:20,name: 'Tornado'}
];
- 然后这个时候我们需要将这个类导入到我们显示的heroes的ts类文件中显示:这里是我们用了HEROES代替名
import { HEROES } from '../mock-heroes';
//接着在此ts类中export中添加代码用来绑定:
heroes = HEROES;
- 其次我们需要将这些英雄都要显示出来,我们利用之前学到的*ngFor
//我们在heroes.component.html中最上面添加此代码即可,
//其中我们利用ul标签的无序性和li标签用来显示单个英雄
//click外面的圆括号会让Angular监听这个<li>元素的click事件,
//当用户点击<li>时,Angular就会执行表达式onSelect(hero);
//onSelect是一个方法,在下面我们会找到。
<h2>My Heroes</h2>
<ul class="heroes">
<li *ngFor="let hero of heroes"
[class.selected]="hero === selectedHero"
(click)="onSelect(hero)">
<span class="badge">{{hero.id}}</span> {{hero.name}}
</li>
</ul>
//注意:其中的[class.selected]="hero === selectedHero"
//是为了添加和移除css类的,
//目的就是当我们点击其中一个英雄名的时候会产生不同的效果。
- 我们在heroes的ts文件中添加我们刚刚的onSelect方法:
//将此方法写在export中的最后面即可:
onSelect(hero:Hero): void {
this.selectedHero=hero;
}
- 到了我们关键的步骤了,我们需要书写CSS文件了
/* HeroesComponent's private CSS styles */
.selected {
background-color: #CFD8DC !important;
color: white;
}
.heroes {
margin: 0 0 2em 0;
list-style-type: none;
padding: 0;
width: 15em;
}
.heroes li {
cursor: pointer;
position: relative;
left: 0;
background-color: #EEE;
margin: .5em;
padding: .3em 0;
height: 1.6em;
border-radius: 4px;
}
.heroes li.selected:hover {
background-color: #BBD8DC !important;
color: white;
}
.heroes li:hover {
color: #607D8B;
background-color: #DDD;
left: .1em;
}
.heroes .text {
position: relative;
top: -3px;
}
.heroes .badge {
display: inline-block;
font-size: small;
color: white;
padding: 0.8em 0.7em 0 0.7em;
background-color: #607D8B;
line-height: 1em;
position: relative;
left: -1px;
top: -4px;
height: 1.8em;
margin-right: .8em;
border-radius: 4px 0 0 4px;
}
- 这个时候我们会继续上一次的英雄编辑器的代码做一下修改,你可以将之前的代码去掉,然后将此代码粘贴上去即可。并且现在我们需要使用*ngIf隐藏我们的空白详情,
//将次代码放在heroes中的html的最后即可,html总共就是这个还有上面写过的两段代码。
<div *ngIf="selectedHero">
<h2>{{selectedHero.name | uppercase}} Details</h2>
<div><span>id: </span>{{selectedHero.id}}</div>
<div>
<label>name:
<input [(ngModel)]="selectedHero.name" placeholder="name">
</label>
</div>
</div>
小结
此次我们通过reoes组件设计出了我们的英雄榜,虽然此次我们只添加了一个ts文件,以及我们用到了新的css和之前的ts和html文件(这里都是指heroes中的),但是我们这次的效果和逻辑非常的清晰,接下来我们会介绍我们的主从组件哦,请期待。。。