Angular4 中常用的指令入门总结

前言

本文主要给大家介绍了关于Angular4 常用指令的相关内容分享出来供大家参考学习,下面来一起看看详细的介绍:

NgIf

rush:xhtml;">

NgSwitch

有时候需要根据不同的条件,渲染不同的元素,此时我们可以使用多个 ngIf 来实现。

rush:xhtml;">

如果 myVar 的可选值多了一个 'C',就得相应增加判断逻辑:

rush:xhtml;">

可以发现 Var is something else 的判断逻辑,会随着 myVar 可选值的新增,变得越来越复杂。遇到这种情景,我们可以使用 ngSwitch 指令。

rush:xhtml;">
Var is something else

NgStyle

NgStyle 让我们可以方便得通过 Angular 表达式,设置 DOM 元素的 CSS 属性

1、设置元素的背景颜色

rush:xhtml;">
Use fixed yellow background

2、设置元素的字体大小

rush:js;">

NgStyle 支持通过键值对的形式设置 DOM 元素的样式:

rush:xhtml;">

注意到 background-color 需要使用单引号,而 color 不需要。这其中的原因是,ng-style 要求的参数是一个 Javascript 对象,color 是一个有效的 key,而 background-color 不是一个有效的 key ,所以需要添加 ''。

NgClass

NgClass 接收一个对象字面量,对象的 key 是 CSS class 的名称,value 的值是 truthy/falsy 的值,表示是否应用该样式。

1、CSS Class

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

2、HTML

rush:xhtml;">

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

<div[ngClass]="{'bordered-Box': false}">
Class names contains dashes must use single quote

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

NgFor

NgFor 指令用来根据集合(数组) ,创建 DOM 元素,类似于 ng1 中 ng-repeat 指令

rush:xhtml;">

使用 trackBy 提高列表的性能

rush:js;"> @Component({ selector: 'my-app',template: `

NgNonBindable

ngNonBindable 指令用于告诉 Angular 编译器,无需编译页面中某个特定的HTML代码片段。

rush:xhtml;">
← This is what {{ content }} rendered

Angular 4.x 新特性

If...Else Template Conditions

语法

rush:xhtml;">

使用示例

rush:xhtml;">

You are not allowed to see our secret