Skip to content
 

数据绑定

更新: 9/4/2025字数: 0 字 时长: 0 分钟

1、html 绑定

使用插值表达式 同 vue;可以执行算术运算,比较运算,逻辑运算,三目运算,调用函数;但是不能使用 new 关键字和 JSON 序列化

2、属性绑定

html
<p title="{{ obj.name }}">这是一段文本</p>
或者
<p [title]="obj.name">这是一段文本</p>

3、事件绑定

html
<button (click)="nameClick()">{{ obj.name }}</button>

4、指令绑定

NgFor 指令:

列表循环,需要在装饰器中导入 imports: [NgFor],使用如下:

html
import {NgFor} from '@angular/common'; @Component({ selector: 'app-first', imports: [NgFor], ... })
<ul>
  <li *ngFor="let item of list;let i=index">{{ i + 1 }} - {{ item.name }}</li>
</ul>

NgIf 指令:

NgIffalse 时,Angular 会从 DOM 中移除一个元素及其子元素。然后 Angular 会释放它们的组件,以释放内存和资源。

html
<p *ngIf="isActive">此段内容仅付费用户观看!</p>

NgClass 指令:

使用 ngClass 同时添加或删除多个 CSS 类。

html
<div [ngClass]="isSpecial ? 'special' : ''">This div is special</div>

添加多个类,值为 true 的保存

js
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,
    };
  }
html
<div [ngClass]="currentClasses">This div is initially saveable, unchanged, and special.</div>

NgStyle 指令:

设置内联样式;根据组件的状态同时设置多个内联样式。

js
currentStyles: Record<string, string> = {};
...
  setCurrentStyles() {
    // CSS styles: set per current state of component properties
    this.currentStyles = {
      'font-style': this.canSave ? 'italic' : 'normal',
      'font-weight': !this.isUnchanged ? 'bold' : 'normal',
      'font-size': this.isSpecial ? '24px' : '12px',
    };
  }
html
<div [ngStyle]="currentStyles">This div is initially italic, normal weight, and extra large (24px).</div>

NgSwitch 指令:

NgSwitch 根据一个切换条件从多个可能的元素中显示其中一个元素。Angular 只把选中的元素放入 DOM 中。

NgSwitch 是一组包含三个指令的集合:

NgSwitch 指令详情
NgSwitch一个改变其伴随指令行为的属性型指令。
NgSwitchCase结构型指令,当其绑定值等于切换值时,将它的元素添加到 DOM 中,反之则移除其绑定值。
NgSwitchDefault结构型指令,当没有选中的 NgSwitchCase 时,将它的元素添加到 DOM 中。
html
<div [ngSwitch]="currentItem.feature">
  <app-stout-item *ngSwitchCase="'stout'" [item]="currentItem"></app-stout-item>
  <app-device-item *ngSwitchCase="'slim'" [item]="currentItem"></app-device-item>
  <app-lost-item *ngSwitchCase="'vintage'" [item]="currentItem"></app-lost-item>
  <app-best-item *ngSwitchCase="'bright'" [item]="currentItem"></app-best-item>
  ...
  <app-unknown-item *ngSwitchDefault [item]="currentItem"></app-unknown-item>
</div>

5、双向数据绑定[(ngModel = 'value')]

NgModel 指令

使用 NgModel 指令来显示数据属性,并在用户进行更改时更新该属性。可以实现表单的双向绑定。

js
import { Component } from '@angular/core';
import {FormsModule} from '@angular/forms'; // 必须要引入并使用这个模块
@Component({
  selector: 'app-first',
  imports: [NgFor,NgIf,FormsModule],
  ...
})
html
<div>
  <label for="example-ngModel">[(ngModel)]:</label>
  <input [(ngModel)]="inputValue" (ngModelChange)="setUppercaseName($event)" id="example-ngModel" />
  <p>当前用户输入的值:{{inputValue}}</p>
</div>

我见青山多妩媚,料青山见我应如是。