第四章 内建组件

介绍

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只有少数几个内建组件,但是可以动态组合这些组件,完成一个项目.

时间: 2024-08-01 02:29:10

第四章 内建组件的相关文章

【ALearning】第四章 Android Layout组件布局(二)

前面我们分别介绍和学习了LinearLayout(线性布局).FrameLayout(单帧布局)和AbsoluteLayout(绝对布局).这次我们要进行RelativeLayout(相对布局)和TableLayout(表格布局)的学习.这部分是很重要的知识点.RelativeLayout是开发过程中强烈建议使用的,而TableLayout是满足一些特定需求时(常见表格显示,但不局限于此)需要使用. [博客专栏:http://blog.csdn.net/column/details/alearn

Android学习笔记—第四章 Android开发组件2

第四章 Android开发组件2 列表类组件 (1)ListView组件:以垂直列表的形式列出需要显示的列表项 相关属性: a. android:divider  用于为列表视图设置分隔条,可以用颜色或者图片资源 b. android:dividerHeight  设置分隔条的高度 c. android:entries  通过数组资源为ListView指定列表项 d. android:footerDividersEnabled  设置是否在footerView之前绘制分隔条,默认为true. e

javascript 对象初探 (四)--- 内建对象Array

 我们不要去纠结神马是内建对象,神马是內建构造器.到后来你们便会发现其实她们都是对象. Array()是一个构建数组的內建构造器函数: var arr = new Array(); 与下面的是等效的: var arr = []; //数组文本表识法 无论数组是以神马方式创建的,我们都可以照常向里面添加元素. arr[0] = 1; arr[1] = 2; console.log(arr) // [1, 2] 当我们使用构造器函数Array()创建数组时,也可以通过传值的方式为其添加元素: var

【ALearning】第四章 Android Layout组件布局(一)

在本章中,我们将Android学习组件布局.在前面的章节,我们也开始使用LinearLayout布局.然后我们在布局文件更加具体的学习和理解,会. Android的界面是有布局和组件协同完毕的,布局好比是建筑里的框架,而组件则相当于建筑里的砖瓦.组件依照布局的要求依次排列.就组成了用户所看见的界面. Android的五大布局各自是LinearLayout(线性布局).FrameLayout(单帧布局).RelativeLayout(相对布局).AbsoluteLayout(绝对布局)和Table

[Learn AF3]第四章 App framework组件之Button

Button    组件名称:Button     是否js控件:否     使用说明:如果说panel组件是af3的“核心(heart of the ui)”,那么Button就是af中的五虎上将之一,在af app中使用的频率非常之高. 1,在af中你可以让任何元素表现的像个button控件,比如下面的三种元素,将会呈现的一模一样: 1 <a class="button">Home</a> 2 <span class="button"

Scala 编程(四)内建控制结构

if 表达式 Scala 的 if 如同许多其它语言中的一样工作.它测试一个状态并据其是否为真,执行两个分支中的一个: var filename = "default.txt" if (!args.isEmpty) filename = args(0) 由于 Scala 的 if 是能返回值的表达式,可以改成用 val 的更函数式的风格: val filename = if (!args.isEmpty) args(0) else "default.txt" 使用

四十四 常用内建模块 struct

准确地讲,Python没有专门处理字节的数据类型.但由于str既是字符串,又可以表示字节,所以,字节数组=str.而在C语言中,我们可以很方便地用struct.union来处理字节,以及字节和int,float的转换. 在Python中,比方说要把一个32位无符号整数变成字节,也就是4个长度的bytes,你得配合位运算符这么写: >>> n = 10240099 >>> b1 = (n & 0xff000000) >> 24 >>>

python基础(文件输入/输出 内建类型 字典操作使用方法)

本文主要介绍了python基础入门,包括文件输入/输出.内建类型.字典操作等使用方法 一.变量和表达式 代码如下: >>> 1 + 1 2>>> print 'hello world' hello world>>> x = 1               >>> y = 2>>> x + y3 Python是强类型语言,无法根据上下文自动解析转换成合适的类型. Python是一种动态语言,在程序运行过程中,同一个变量

OpenGL ES着色器语言之语句和结构体(官方文档第六章)内建变量(官方文档第七、八章)

OpenGL ES着色器语言之语句和结构体(官方文档第六章) OpenGL ES着色器语言的程序块基本构成如下: 语句和声明 函数定义 选择(if-else) 迭代(for, while, do-while) 跳跃(discard, return, break, continue) 6.1函数定义   着色器是由一系列全局声明和函数定义组成的.函数声明规范如下: // prototype returnType functionName (type0 arg0, type1 arg1, ...,