Angular学习笔记四——显示数据及添加事件
1.显示用户列表数据
在users.component.ts中添加users属性:
import { Component, OnInit } from '@angular/core';
import { User } from '../../model/user';
@Component({
selector: 'app-users',
templateUrl: './users.component.html',
styleUrls: ['./users.component.css']
})
export class UsersComponent implements OnInit {
users: User[] = [
{ id: 1, name: '张三' },
{ id: 2, name: '李四' },
{ id: 3, name: '王五' },
{ id: 4, name: '赵六' },
{ id: 5, name: '田七' },
{ id: 6, name: '杜八' }
];
constructor() { }
ngOnInit(): void {
}
}
在users.component.html中,使用*ngFor来显示数据:
<div>
<h2>我的用户</h2>
<ul class="users">
<li *ngFor="let user of users">
<span class="badge">{{user.id}}</span>{{user.name}}
</li>
</ul>
</div>
为了使页面更加美观,添加一些样式:
.users {
margin: 0 0 2em 0;
list-style-type: none;
padding: 0;
width: 15em;
}
.users li {
position: relative;
cursor: pointer;
background-color: #EEE;
margin: .5em;
padding: .3em 0;
height: 1.6em;
border-radius: 4px;
}
.users li:hover {
color: #607D8B;
background-color: #DDD;
left: .1em;
}
.users .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;
min-width: 16px;
text-align: right;
margin-right: .8em;
border-radius: 4px 0 0 4px;
}
刷新浏览器页面,效果如下:
2.添加事件
在users.component.ts中添加selectUser属性,用来定义当前选中的用户。添加onSelect(user)方法将当前选中的用户赋值给输入框。
import { Component, OnInit } from '@angular/core';
import { User } from '../../model/user';
@Component({
selector: 'app-users',
templateUrl: './users.component.html',
styleUrls: ['./users.component.css']
})
export class UsersComponent implements OnInit {
selectUser: User = new User();
users: User[] = [
{ id: 1, name: '张三' },
{ id: 2, name: '李四' },
{ id: 3, name: '王五' },
{ id: 4, name: '赵六' },
{ id: 5, name: '田七' },
{ id: 6, name: '杜八' }
];
constructor() { }
ngOnInit(): void {
}
onSelect(user: User): void {
this.selectUser = user;
}
}
在users.component.html中添加click事件。click外面的圆括号会让Angular监听li标签的click事件。当用户点击li标签时,Angular就会执行表达式onSelect(user)。
<div>
<h2>我的用户</h2>
<ul class="users">
<li *ngFor="let user of users" (click)="onSelect(user)">
<span class="badge">{{user.id}}</span>{{user.name}}
</li>
</ul>
</div>
<h2>{{selectUser.name}}</h2>
<div *ngIf="selectUser">
<div>
<span>id:</span>{{selectUser.id}}
</div>
<label>
name:
<input [(ngModel)]="selectUser.name">
</label>
</div>
刷新浏览器: 选中某一个用户,可将该用户的编号和名字赋值给下方的id和name。
|