第四章 内建组件

注:学习使用,禁止转载

介绍

angular2提供了很多内建的组件,在这一章,我们会分别介绍它们,并展示一些怎么使用它们的例子.

:fa-info-circle:内建组件可以直接导入到项目中来,而不需要像我们前面介绍一样使用directives导入

NgIf

当你想要根据一个特定的条件显示或者隐藏一个组件的时候,你可以使用NgIf,条件是一个返回boolean类型的ng2的表达式.
如果表达式返回false,元素将从DOM树种移除,如果为true,则会显示.

<div *ngIf="false" > </div> <!-- 绝不显示 -->
< div * ngIf="a > b" > </div> <!-- 当A大于B的时候显示 -->
< div * ngIf="str == 'yes'" > </div> <!-- 如果字符串值为yes的时候显示 -->
< div * ngIf="myFunc()" > </div> <!-- 如果myFunc函数返回true的时候显示 -->

:fa-info-circle:如果你有使用ng1的经验,你可能会使用ngIf.在ng2中,你可以直接替换.另一方面,你也可以选择ng2提供的非内建ng-show.如果你的目标是改变某个元素的CSS显示,你也可以是使用ng-style或者class属性,这些将在后面介绍

NgSwich

有时,你想要去根据不同的条件显示不同的元素,你可以重复使用NgIf来完成.

<div class="container">
    <div *ngIf="myVar == 'A'">Var is A</div>
    <div *ngIf="myVar == 'B'">Var is B</div>
    <div *ngIf="myVar != 'A' && myVar != 'B'">Var is something else</div>
</div>

像你看到的一样,当既不是A也不是B的时候,看起来是不太好看的.这个如果有一个else的选项就好了.另外,如果条件提交越来越多,这个例子会变得越来越复杂.

为了描述这种复杂清单,考虑一个具有C的例子,代码如下:

<div class="container">
    <div *ngIf="myVar == 'A'">Var is A</div>
    <div *ngIf="myVar == 'B'">Var is B</div>
    <div *ngIf="myVar == 'C'">Var is C</div>
    <div *ngIf="myVar != 'A' && myVar != 'B' && myVar != 'C'">Var is something els\ e
    </div>
  </div>

为了简化这个操作,ng2提供了ngSwitch来处理这种问题.
如果你熟悉switch语法,ngSwitch是很好理解的,它跟switch的原理是一样的.

这个组件的理念是:使用一个简单表达式作为条件,基于这个表达式的值来做操作.

过程如下:

  • 使用ngSwitchWhen指令描述表达式的值
  • 处理所有的可能,其他可能使用ngSwitchDefault来表述

让我们看看使用NgSwitch的代码:

<div class="container" [ngSwitch]="myVar">
    <div *ngSwitchWhen="'A'">Var is A</div>
    <div *ngSwitchWhen="'B'">Var is B</div>
    <div *ngSwitchDefault>Var is something else</div>
  </div>

如果我们插入一个C的值,代码会变成下面这样:

<div class="container" [ngSwitch]="myVar">
    <div *ngSwitchWhen="'A'">Var is A</div>
    <div *ngSwitchWhen="'B'">Var is B</div>
    <div *ngSwitchWhen="'C'">Var is C</div>
    <div *ngSwitchDefault>Var is something else</div>
  </div>

我们不会去关注默认条件究竟是什么.
ngSwitchDefault是可选的,如果我们不写出来,当什么条件都不满足的时候,将会什么都不显示.

你也可以根据不同的元素定义一些相同的ngSwitchWhen,下面是一个例子:

code/built_in_components/ng_switch/app.ts

@Component({
  selector: 'switch-sample-app',
  template: `
    <h4 class="ui horizontal divider header">
      Current choice is {{ choice }}
    </h4>

    <div class="ui raised segment">
      <ul [ngSwitch]="choice">
        <li *ngSwitchWhen="1">First choice</li>
        <li *ngSwitchWhen="2">Second choice</li>
        <li *ngSwitchWhen="3">Third choice</li>
        <li *ngSwitchWhen="4">Fourth choice</li>
        <li *ngSwitchWhen="2">Second choice, again</li>
        <li *ngSwitchDefault>Default choice</li>
      </ul>
    </div>

    <div style="margin-top: 20px;">
      <button class="ui primary button" (click)="nextChoice()">
        Next choice
      </button>
    </div>
  `
})
class SwitchSampleApp {
  choice: number;

  constructor() {
    this.choice = 1;
  }

  nextChoice() {
    this.choice += 1;

    if (this.choice > 5) {
      this.choice = 1;
    }
  }
}

ngSwitchWhen的另一个特性是不限制你去使用相同的条件一次,你可以是相同的条件多次.

NgStyle

使用NgStyle,你可以使用ng2表达式来设置给定元素的CSS属性.
使用这个指令的最简单方式是:[style.]=”value”,比如:

code/built_in_components/ng_style/app.ts
<div [style.background-color]="'yellow'"> Uses fixed yellow background
</div>

这个代码的意思是设置div的背景颜色为yellow.
使用NgStyle的另一种方式就是通过设置key-value对来设置多个CSS属性的值,比如:

code/built_in_components/ng_style/app.ts
<div [ngStyle]="{color: 'white', 'background-color': 'blue'}"> Uses fixed white text on blue background
</div>

:fa-info-circle:注意上面的表达式,color没有使用引号,而background-color使用了引号,是因为,NgStyle的表达式是一个JavaScript的表达式,color是一个正常变量名字,但是background-color不是一个正常的变量名字,它代表background减去color,但是如果使用引号,就可以了.

这里我们设置了color和background-color的值.

但是在我们的实际项目中,一般我们都会使用动态值而不是固定值.如下,我们定义两个输入框:

code/built_in_components/ng_style/app.ts
<div class="ui input">
    <input type="text" name="color" value="{{color}}" #colorinput>
  </div>
  <div class="ui input">
    <input type="text" name="fontSize" value="{{fontSize}}" #fontinput>
  </div>

然后,我们使用它们的值去设置三个元素的CSS属性.
第一个,通过fontSize设置字体大小,如下:

code/built_in_components/ng_style/app.ts
<div>
  <span [ngStyle]="{color: 'red'}" [style.font-size.px]="fontSize">
red text
  </span>
</div>

上面需要注意的是[style.font-size.px],它指明了单位.
.px说明了我们希望后面的数字表示的单位是px,当然也可以使用[style.fontSize.em],[style.fontSize.%]

另外两个元素使用#colorinput设置文本及背景颜色,如下:

code/built_in_components/ng_style/app.ts
<h4 class="ui horizontal divider header"> ngStyle with object property from variable
</h4>
<div>
  <span [ngStyle]="{color: colorinput.value}">
{{ colorinput.value }} text </span>
</div>
<h4 class="ui horizontal divider header"> style from variable
</h4>
<div [style.background-color]="colorinput.value" style="color: white;">
  {{ colorinput.value }} background
</div>

另一种方式,当我们使用apply setting按钮的时候,会调用apply去设置新的值:
code/built_in_components/ng_style/app.ts

apply(color, fontSize) {
    this.color = color;
    this.fontSize = fontSize;
}

NgClass

NgClass指令可以使你能够动态修改给定元素的CSS类.

:fa-info-circle:如果你使用过ng1,这个跟ng1是很相似的.

使用这个指令的一种方式就是传递一个对象常量,对象的key代表的是类名,对象的值是一个boolean值,代表该class是否应用于指定的元素.

假设我们有一个bordered的CSS类,如下:
code/built_in_components/class/styles.css

.bordered {
border: 1px dashed black; background-color: #eee;
}

然后增加两个div元素,一个具有bordered类,一个没有:
code/built_in_components/ng_class/app.ts

<div [ngClass]="{bordered: false}">This is never bordered</div> 
<div [ngClass]="{bordered: true}">This is always bordered</div>

跟预想的一样,渲染如下:

输入图片说明

当然,更加有用的使用方式是使用动态绑定:

code/built_in_components/ng_class/app.ts

<div [ngClass]="{bordered: isBordered}">
Using object literal. Border {{ isBordered ? "ON" : "OFF" }}
</div>

另外,我们也可以在我们的组件类中定义一个对象:

code/built_in_components/ng_class/app.ts

toggleBorder() {
    this.isBordered = !this.isBordered;
    this.classesObj = {
      bordered: this.isBordered
    };
}

然后直接使用这个对象:
code/built_in_components/ng_class/app.ts

<div [ngClass]="classesObj">
Using object var. Border {{ classesObj.bordered ? "ON" : "OFF" }}
</div>

:fa-info-circle:注意,当你的key中包含’-‘符号时,一定记得要加引号,不然是非法的.

我们也可以是使用数组来表示哪些类需要添加到我们的元素上:

ode/built_in_components/ng_class/app.ts

<div class="base" [ngClass]="['blue', 'round']"> 
    This will always have a blue background and round corners
</div>

也可以在我们的组件代码中定义一个数组变量:

this.classList = ['blue', 'round'];

然后将其传递进去:
code/built_in_components/ng_class/app.ts

<div class="base" [ngClass]="classList">
This is {{ classList.indexOf('blue') > -1 ? "" : "NOT" }} blue and {{ classList.indexOf('round') > -1 ? "" : "NOT" }} round
</div>

注意,使用class属性标注的类,始终会添加到元素上面,如:
code/built_in_components/ng_class/app.ts

<div class="base" [ngClass]="['blue', 'round']"> 
    This will always have a blue background and round corners
</div>

这个元素会有三个类,base,blue和round.

输入图片说明

NgFor

这个指令的意思就是重复渲染一个DOM元素,并且每次传递不同的参数给它.

:fa-info-circle:这个指令与ng-repeat一样.

语法为:*ngFor=”let item of items”

  • let item标识了每次接受元素的变量
  • items是来自组件的数组变量

假设我们有下面的数组:

this.cities = ['Miami', 'Sao Paulo', 'New York'];

然后,我们可以像下面这样写:

code/built_in_components/ng_for/app.ts

<h4 class="ui horizontal divider header"> 
    Simple list of strings
</h4>
<div class="ui list" *ngFor="let c of cities"> 
    <div class="item">{{ c }}</div>
</div>

它会像下面这样渲染每个城市:

输入图片说明

也可以迭代一个数组对象:

code/built_in_components/ng_for/app.ts

this.people = [
      { name: 'Anderson', age: 35, city: 'Sao Paulo' },
      { name: 'John', age: 12, city: 'Miami' },
      { name: 'Peter', age: 22, city: 'New York' }
];

然后基于每列渲染一个表格:

code/built_in_components/ng_for/app.ts

 <h4 class="ui horizontal divider header"> List of objects</h4>
  <table class="ui celled table">
    <thead>
      <tr>
        <th>Name</th>
        <th>Age</th>
        <th>City</th>
      </tr>
    </thead>
    <tr *ngFor="let p of people">
      <td>{{ p.name }}</td>
      <td>{{ p.age }}</td>
      <td>{{ p.city }}</td>
    </tr>
  </table>

结果如下:

输入图片说明

也可以与嵌套数组工作:

code/built_in_components/ng_for/app.ts

this.peopleByCity = [
  {
    city: 'Miami',
    people: [
      { name: 'John', age: 12 },
      { name: 'Angel', age: 22 }
    ]
  }, {
    city: 'Sao Paulo',
    people: [
      { name: 'Anderson', age: 35 },
      { name: 'Felipe', age: 36 }
    ]
  }];

我们可以是使用NgFor仅仅渲染城市:

code/built_in_components/ng_for/app.ts

<div *ngFor="let item of peopleByCity">
<h2 class="ui header">{{ item.city }}</h2>

也可以渲染每个城市的嵌套人员:
code/built_in_components/ng_for/app.ts

<table class="ui celled table">
    <thead>
      <tr>
        <th>Name</th>
        <th>Age</th>
      </tr>
    </thead>
    <tr *ngFor="let p of item.people">
      <td>{{ p.name }}</td>
      <td>{{ p.age }}</td>
    </tr>
  </table>

模板代码如下:
code/built_in_components/ng_for/app.ts

<h4 class="ui horizontal divider header"> Nested data
</h4>
  <div *ngFor="let item of peopleByCity">
    <h2 class="ui header">{{ item.city }}</h2>
    <table class="ui celled table">
      <thead>
        <tr>
          <th>Name</th>
          <th>Age</th>
        </tr>
      </thead>
      <tr *ngFor="let p of item.people">
        <td>{{ p.name }}</td>
        <td>{{ p.age }}</td>
      </tr>
    </table>
  </div>

渲染结果如下:

输入图片说明

过去索引

有时候,在迭代数组的时候,我们需要每个元素的索引.
你可以使用 let idx = index语法获取索引,它添加到ng-for后面,如下:
code/built_in_components/ng_for/app.ts

<div class="ui list" *ngFor="let c of cities; let num = index"> 
    <div class="item">{{ num+1 }} - {{ c }}</div>
</div>

在位置前,我增加了城市序号,渲染如下:

输入图片说明

NgNonBindable

当我们需要告诉angular不要去编辑部分页面的时候,如下:
code/built_in_components/ng_non_bindable/app.ts

  <div>
    <span class="bordered">{{ content }}</span> <span class="pre" ngNonBindable>
&larr; This  is what {{ content }} rendered
    </span>
  </div>

渲染如下:

输入图片说明

可以看出,{{ content }}没有编译与绑定.

总结

ng2只有少数几个内建组件,但是可以动态组合这些组件,完成一个项目.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值