Angular 属性绑定
在Angular 7中,属性绑定用于传递组件类(component.ts)中的数据并在用户中设置给定元素的值-end(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>
在这里,
{{allowNewServer}}
指定字符串插值。
输出:
我们也可以使用属性绑定来完成相同的任务。
示例:
<p>
Server2 is also working fine.
</p>
<button class="btn btn-primary"
[disabled]="!allowNewServer" >Add Server</button>
<h3 [innerText]= "allowNewServer"></h3>
输出:
它还将为您提供相同的结果:
但是,字符串插值有一些限制。稍后,我们将学习在何处使用字符串插值以及在何处进行属性绑定。