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

angular 7的属性绑定

点击下载

本文概述

在Angular 7中,属性绑定用于传递来自组件类(component.ts)的数据,并在用户端(component.html)中设置给定元素的值。

属性绑定是单向数据绑定的一个示例,其中数据从组件传输到类。

属性绑定的主要优点是它可以帮助你控制元素的属性。

例如

我们将向“ component.html”页面添加一个按钮。

<p>
  Server2 is also working fine.
</p>
<button class="btn btn-primary">Add Server</button>

component.ts文件:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-server2', templateUrl: './server2.component.html', styleUrls: ['./server2.component.css']
})
export class Server2Component implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

输出:

让我们看看属性绑定是如何工作的?

首先,我们将通过使用disabled属性来禁用按钮。

<p>
  Server2 is also working fine.
</p>
<button class="btn btn-primary" disabled>Add Server</button>

现在,该按钮已禁用。

让我们在“ component.ts”文件中添加一个新属性“ allowNewServer”,它将在特定(可设置)时间后自动禁用按钮。

component.ts文件:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-server2', templateUrl: './server2.component.html', styleUrls: ['./server2.component.css']
})
export class Server2Component implements OnInit {
 allowNewServer = false;

  constructor() {
    setTimeout(() =>{
      this.allowNewServer = true;
    }, 5000);
  }

  ngOnInit() {
  }

}

component.html文件:

<p>
  Server2 is also working fine.
</p>
<button class="btn btn-primary"
        [disabled]="allowNewServer">Add Server</button>

在这里,我们将时间设置为5000毫秒或5秒。 5秒钟后,该按钮将自动禁用。

这是属性绑定的示例,其中属性是动态绑定的。

输出:

<p>
  Server2 is also working fine.
</p>
<button class="btn btn-primary"
        [disabled]="!allowNewServer" >Add Server</button>

通过使用上面的代码,你可以在5秒钟后自动允许禁用的按钮。

属性绑定与字符串插值

对于数据绑定情况,我们可以使用属性绑定以及字符串插值。例如,让我们在上面的示例中添加字符串插值。

<p>
  Server2 is also working fine.
</p>
<button class="btn btn-primary"
        [disabled]="!allowNewServer" >Add Server</button>
<h3>{{allowNewServer}}</h3>

在这里,<h3> {{allowNewServer}} </ h3>指定字符串插值。

输出:

我们也可以通过使用属性绑定来完成相同的任务。

例:

<p>
  Server2 is also working fine.
</p>
<button class="btn btn-primary"
        [disabled]="!allowNewServer" >Add Server</button>
<h3 [innerText]= "allowNewServer"></h3>

输出:

它还将为你提供相同的结果:

但是,字符串插值有一些限制。稍后,我们将学习在哪里使用字符串插值以及在哪里进行属性绑定。


赞(0)
未经允许不得转载:srcmini » angular 7的属性绑定

评论 抢沙发

评论前必须登录!