最常见的属性指令如下:
COMMON DIRECTIVES | DETAILS |
---|---|
NgClass | Adds and removes a set of CSS classes. 添加和删除一组 CSS 类 |
NgStyle | Adds and removes a set of HTML styles. 添加和删除一组 HTML 样式 |
NgModel | Adds two-way data binding to an HTML form element. 为 HTML 表单元素添加双向数据绑定 |
NgClass
要使用 NgClass,请导入 CommonModule 并将其添加到组件的导入列表中
import {CommonModule} from '@angular/common';
/* . . . */
@Component({
standalone: true,
/* . . . */
imports: [
CommonModule, // <-- import into the component
/* . . . */
],
})
export class AppComponent implements OnInit {
/* . . . */
}
在表达式中使用 NgClass
<!-- toggle the "special" class on/off with a property -->
<div [ngClass]="isSpecial ? 'special' : ''">This div is special</div>
<div [ngClass]="currentClasses">This div is initially saveable, unchanged, and special.</div>
currentClasses: Record<string, boolean> = {};
/* . . . */
setCurrentClasses() {
// CSS classes: added/removed per current state of component properties
this.currentClasses = {
saveable: this.canSave,
modified: !this.isUnchanged,
special: this.isSpecial,
};
}
要添加或删除单个类,请使用类绑定而不是 NgClass,这样会更简单,点击查看详情
NgStyle
要使用 NgStyle,请导入 CommonModule 并将其添加到组件的导入列表中
import {CommonModule} from '@angular/common';
/* . . . */
@Component({
standalone: true,
/* . . . */
imports: [
CommonModule, // <-- import into the component
/* . . . */
],
})
export class AppComponent implements OnInit {
/* . . . */
}
<div [ngStyle]="currentStyles">
This div is initially italic, normal weight, and extra large (24px).
</div>
NgModel
导入 FormsModule 并将其添加到 AppComponent 的导入列表中
import {FormsModule} from '@angular/forms'; // <--- JavaScript import from Angular
/* . . . */
@Component({
standalone: true,
/* . . . */
imports: [
CommonModule, // <-- import into the component
FormsModule, // <--- import into the component
/* . . . */
],
})
export class AppComponent implements OnInit {
/* . . . */
}
<label for="example-ngModel">[(ngModel)]:</label>
<input [(ngModel)]="currentItem.name" id="example-ngModel">
要自定义配置,可编写扩展表单,将属性绑定和事件绑定分开。使用属性绑定设置属性,使用事件绑定响应变化。以下示例将 <input> 值更改为大写字母
<input [ngModel]="currentItem.name" (ngModelChange)="setUppercaseName($event)" id="example-uppercase">