Angular内置属性型指令
属性型指令会监听和修改其他HTML元素或组件的行为、元素属性(Attribute)、DOM属性(Property)。他们通常会作为HTML属性的名称而应用在元素上。
更多Angular模块,比如:RouterModel和FormsModule都定义了自己的属性型指令。
几个常用的属性型指令:
1.NgClass--添加或移除一组CSS类
2.NgClass---添加或移除医嘱CSS样式
3.NgModel---双向绑定到HTML表单元素。
一、NgClass
我们经常用用到添加或删除CSS类的方式来控制元素如何显示。通过绑定NgClass,可以同时添加或移除多个类。
1.CSS类绑定 ,添加或删除单个类的最佳途径
<div [class.alert]="isAlert" [class.alert-success]="isSuccess">
这是alert信息展示
</div>
isAlert = true;
isSuccess = true;
2.NgClass 同时添加或移除多个CSS类
<div [ngClass]="classList">
ngClass指令使用
</div>
this.classList = {
alert: this.isAlert,
["alert-success"]: this.isSuccess,
["fade in"]: this.isAlert
};
注意:
changeOne() {
//此处修改this.isAlert属性,不会级联修改 this.classList中的值
this.isAlert = !this.isAlert;
this.isSuccess = !this.isSuccess;
}
二、NgStyle
我们可以根据组件的状态动态设置内联样式。NgStyle 绑定可以同时设置多个内联样式。
1.样式绑定 是设置单一样式的简单方式
<div class="tab-pane active" id="one">
<p [style.color]="isSuccess?'green':'red'"
[style.font-size]="isSuccess?'bold':'lighter'">这是标签one</p>
</div>
2.NgStyle 需要绑定到一个key:value控制对象。
对象的每个key是样式名,balue是样式的值。
<p [ngStyle]="styleList">
这是标签two
</p>
this.styleList={
'font-weight':'bold',
'font-size':'30px',
color:'red'
}
使用[(ngModel)] 双向绑定到表单元素
<input [(ngModel)]="currentHero.name">
1.使用ngModel时需要FormsModule,使用之前㤇导入该模块
导入FormsModul代码示例:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms'; // <--- JavaScript import from Angular
/* Other imports */
@NgModule({
imports: [
BrowserModule,
FormsModule // <--- import into the NgModule
],
/* Other module metadata */
})
export class AppModule { }
2.ngModel绑定优于绑定到该元素的原生属性
ngModuleChange 可以监听修改后的值,$event用于用户获取修改后的值,
也就是用户的修改触发ngModelChange
<div class="panel panel-primary">
<div class="panel-heading">
<div class="panel-title">NgModel 双向绑定示例1</div>
</div>
<div class="panel-body">
<form>
<div class="form-group">
<label for="" class="content-label">
姓名:
</label>
<input type="text" class="form-control" name="Name"
[(ngModel)]="hero.Name"
(ngModelChange)="setUpper($event)">
</div>
<div class="alert alert-success">
{{hero|json}}
</div>
</form>
</div>
</div>
更多: