上。
要想将NgClass与方法一起使用,需要将方法添加到组件中。如例31中的setCurrentClasses()方法使用一个对象来设置属性currentClasses,该对象根据canSave、isUnchanged、isSpecial等组件属性为true或false来添加或删除三个类。该对象的每个键(key)(如saveable)都是一个类名。如果键(类名)的取值为true,则NgClass添加该类。如果键(类名)的取值为false,则NgClass删除该类。于是,在模板中把NgClass属性绑定到currentClasses,根据它来设置此元素的CSS类。在例31中,Angular会在初始化以及发生更改的情况下应用这些类,即在ngOnInit()方法中进行初始化以及通过单击按钮更改相关属性时调用setCurrentClasses()方法。
【例31】创建文件insidedirective.component.ts的代码
,演示本章的基础知识点。
import {Component} from '@angular/core';
import {Item} from "./item";
@Component({
selector: 'root',//'app-inside-directive',
template: `
NgClass绑定
currentClasses is {{currentClasses | json}}
This div is initially saveable, unchanged, and special.
This div should be {{ canSave ? "": "not"}} saveable,
{{isUnchanged ? "unchanged" : "modified"}} and
{{isSpecial ? "": "not"}} special after clicking "Refresh".
This div is special
Helpful study course
Study course
NgStyle绑定
This div is x-large or smaller.
[ngStyle] binding to currentStyles - CSS property names
currentStyles is {{currentStyles | json}}
This div is initially italic, normal weight, and extra large (24px).
|
|
This div should be {{ canSave ? "italic": "plain"}},
{{isUnchanged ? "normal weight" : "bold"}} and,
{{isSpecial ? "extra large": "normal size"}} after clicking "Refresh".
NgModel双向绑定
Hello, {{nullCustomer.id}}
Hello, {{nullCustomer2}}
{{i + 1}} - {{item.name}}
({{item.id}}) {{item.name}}
I turned the corner
and saw {{item.name}}. I waved
and continued on my way.
NgSwitch Binding
Pick your favorite item
Are you as bright as {{currentItem.name}}?
Highlight me!
Pick a highlight color
Green
Yellow
Cyan
Highlight me!
不会显示2: {{ 1 + 1 }}
This should not evaluate: {{ 1 +1 }}, but will highlight yellow.
(A) This paragraph is displayed because the condition is false.
(B) Although the condition is true,
this paragraph is displayed because appUnless is set to false.