Angular教程

Angular 字符串插值

在Angular中,字符串插值用于在HTML模板上显示动态数据(在用户端)。它使您可以对component.ts文件进行更改,并从那里获取数据到HTML模板(component.html文件)。

例如:

component.ts文件:
import {Component} from '@angular/core';
@Component(
  {selector: 'app-server',
 templateUrl: 'server.component.html'})
export class ServerComponent {
  serverID: number = 10;
    serverStatus: string = 'Online';
}
在这里,我们使用一些值指定了serverID和serverStatus。让我们在" component.html"文件中使用它。
component.html文件:
<p>Server with ID {{serverID}} is {{serverStatus}}. </p>
输出:
字符串插值

字符串插值与属性绑定

字符串插值和属性绑定都用于同一目的,即单向数据绑定。但是问题是如何知道哪一个最适合您的应用程序。
在这里,我们在相似性,差异,安全性和收到的输出方面进行了比较。

相似性字符串插值和属性绑定

字符串插值和属性绑定是关于单向数据绑定的。它们都将一个值从我们的组件传递到HTML元素。
字符串插值
import { Component } from '@angular/core';
@Component({
    selector: 'my-app',
    template: `
                <h1>{{ fullName }}</h1>
              `
})
export class AppComponent {
    fullName: string = 'Robert Junior';
}
您可以在上面的示例中看到Angular从组件中获取fullName属性的值,并使用用于指定插值的花括号将其插入到开始和结束

元素之间。

属性绑定
import { Component } from '@angular/core';
@Component({
    selector: 'my-app',
    template: `
                <h1 [innerHtml]='fullName'></h1>
              `
})
export class AppComponent {
    fullName: string = 'Robert Junior';
}
在"属性绑定"中,了解Angular如何从组件的fullName属性中提取值,并使用

元素的html属性innerHtml将其插入。

字符串插值和属性绑定的两个示例都将提供相同的结果。

字符串插值和属性绑定之间的区别

字符串插值是一种特殊的语法,可通过Angular转换为属性绑定。
当需要连接字符串时,必须使用插值代替属性绑定。

示例:

@Component({
    selector: 'my-app',
    template: `<div>
                    <h1>{{citedExample}}</h1>
                </div>`
})
export class AppComponent {
    citedExample: string = 'Interpolation foe string only';
}
必须将元素属性设置为非字符串数据值时使用属性绑定。

示例:

在下面的示例中,我们通过绑定到布尔属性isDisabled来禁用按钮。
import { Component } from '@angular/core';
@Component({
    selector: 'my-app',
    template: `<div>
    <button [disabled]='isDisabled'>Disable me</button>
                     </div>`
})
export class AppComponent {
isDisabled: boolean = true;
}
如果使用插值而不是属性绑定,则无论isDisabled类属性值是true还是false,该按钮将始终处于禁用状态。
import { Component } from '@angular/core';
@Component({
    selector: 'my-app',
    template: `<div>
    <button disabled='{{isDisabled}}'>Disable Me</button>
                     </div>`
})
export class AppComponent {
isDisabled: boolean = true/false;
}

昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4