转载自 http://www.ngui.cc/news/show-104.html
在 Angular 实际项目中,最常用的指令是 ngIf 和 ngFor 指令。
基础知识
ngIf 指令简介
该指令用于根据表达式的值,动态控制模板内容的显示与隐藏。它与 AngularJS 1.x 中的 ng-if 指令的功能是等价的。
ngIf 指令语法
<div *ngIf="condition">...</div>
ngFor 指令简介
该指令用于基于可迭代对象中的每一项创建相应的模板。它与 AngularJS 1.x 中的 ng-repeat 指令的功能是等价的。
ngFor 指令语法
<li *ngFor="let item of items;">...</li>
ngIf 与 ngFor 指令使用示例
import { Component } from '@angular/core';
interface Address {
province: string;
city: string;
}
@Component({
selector: 'sl-user',
template: `
<h2>大家好,我是{{name}}</h2>
<p>我来自<strong>{{address.province}}</strong>省,
<strong>{{address.city}}</strong>市
</p>
<div *ngIf="showSkills">
<h3>我的技能</h3>
<ul>
<li *ngFor="let skill of skills">
{{skill}}
</li>
</ul>
</div>
` })
export class UserComponent {
name: string;
address: Address;
showSkills: boolean;
skills: string[];
constructor() {
this.name = 'Semlinker';
this.address = {
province: '福建',
city: '厦门' };
this.showSkills = true;
this.skills = ['AngularJS 1.x', 'Angular 2.x', 'Angular 4.x'];
} }