个性化阅读
专注于IT技术分析

angular 7字符串插入

点击下载

本文概述

在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属性的值,并使用花括号将其插入到开始和结束<h1>元素之间,以用于指定插值。

属性绑定

import { Component } from '@angular/core';
@Component({
    selector: 'my-app', template: `
                <h1 [innerHtml]='fullName'></h1>
              `
})
export class AppComponent {
    fullName: string = 'Robert Junior';
}

在“属性绑定”中,查看Angular如何从组件的fullName属性中提取值,并使用<h1>元素的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;
}

赞(0)
未经允许不得转载:srcmini » angular 7字符串插入

评论 抢沙发

评论前必须登录!