{% raw %}
Angular 插值
原文: https://howtodoinjava.com/angular/angular-interpolation/
1. 什么是 Angular 插值?
Angular 插值用于在具有双花括号语法的各个视图模板中显示组件属性。 我们可以在视图中显示所有类型的属性数据字符串,数字,日期,数组,列表或映射。
数据绑定由单向数据绑定和双向数据绑定组成。 插值用于单向数据绑定。 插值会将数据从我们的组件向 HTML 元素沿一个方向移动。
2. Angular 插值语法
在视图模板中显示的属性名称应括在双花括号中,也称为胡子语法。 即:
class AppComponent{propertyName: string;object: DomainObject;}{{ propertyName }}{{ object.propertyName }}
Angular 会自动从组件中提取propertyName和object.propertyName的值,并将这些值插入浏览器。 这些属性更改时,Angular 会更新显示。
3. Angular 插值用法
- 显示简单属性 – 插值可用于显示和求值 HTML 元素标签之间以及属性分配内的文本字符串。
```java
Greetings {{ name }}!
2.**求值算术表达式** – 插值的另一种用法是求值花括号内的算术表达式。```java<h6>{{3 + 5}}</h6> //outputs 8 on HTML browser
- 调用方法并显示返回值 – 我们还可以在插值表达式内的宿主组件视图上调用/调用方法。 ```java import { Component, OnInit } from ‘@angular/core’;
@Component({
selector: ‘app-greet’,
template: <h1>Greetings {{ name }}! </h1>
<h2>Have a good {{ getTime() }}!</h2>,
styleUrls: [‘./greet.component.css’]
})
export class GreetComponent implements OnInit {
name: string = “John Doe”;
getTime(): string { return ‘morning’; }
}
4.**显示数组项** – 我们可以将插值与`ngFor`指令一起使用以显示数组项。```javaexport class DomainObject{constructor(public id: number, public name: string) {//code}}
import { DomainObject } from './domain';@Component({selector: 'app-root',template: `<h1>{{title}}</h1><h2>The name is : {{domainObjectItem.name}}</h2><p>Data Items:</p><ul><li *ngFor="let d of domainObjects">{{ d.name }}</li></ul>`})export class AppComponent{title = 'App Title';domainObjects = [new DomainObject(1, 'A'),new DomainObject(2, 'B'),new DomainObject(3, 'C'),new DomainObject(4, 'D')];domainObjectItem = this.domainObjects[0];}
我们使用内联模板或单独的 HTML 文件进行组件视图,模板数据绑定都具有对组件属性的相同访问权限。
4. Angular 插值示例
通过以下命令,使用@angular/cli创建一个新组件。
//with inline template using '-it' flagng generate component greet -it
上面的命令将使用内联模板生成“greet.component.ts”。 让我们将属性name和time添加到问候组件中,如下所示:
import { Component, OnInit } from '@angular/core';@Component({selector: 'app-greet',template: `<h1>Greetings {{name}}! </h1><h2>Have a good {{time}}!</h2>`,styleUrls: ['./greet.component.css']})export class GreetComponent implements OnInit {name: string = "John Doe";time: string = "morning";}
Angular 会自动从“问候”组件中提取name和time属性的值,并将这些值插入浏览器。 这些属性更改时,Angular 会更新显示。
5. 插值和属性绑定之间的区别
插值是 Angular 转换为属性绑定(一对方括号)的一种特殊语法。 这是属性绑定的便捷替代方法。
另一个主要区别是,要将元素属性设置为非字符串数据值,我们必须使用属性绑定。
在此示例中,将基于'isDisabled'的值禁用或启用OK按钮。 另一方面,无论属性值如何,Cancel按钮将始终被禁用。
export class AppComponent {isDisabled: boolean = true;}<button [disabled]='isDisabled'>OK</button> //Data binding<button disabled='{{isDisabled}}'>Cancel</button> //Interpolation
学习愉快!
{% endraw %}
