目錄
綁定語法概覽
#範本/插值表達式{{}} (基礎,掌握)
屬性綁定(基礎,掌握)
樣式綁定(屬於屬性綁定,基礎,掌握)
#事件綁定(基礎,掌握)
双向绑定(基础,掌握)
内置指令
模板引用变量
输入和输出
管道(基础,掌握)
首頁 web前端 js教程 聊聊angular10中模板如何進行資料綁定?

聊聊angular10中模板如何進行資料綁定?

Aug 03, 2021 am 10:31 AM
angular 範本

本篇文章跟大家介紹一下angular10模板的資料綁定,帶大家了解一下三種綁定語法、模板/插值表達式、屬性綁定、樣式綁定、事件綁定定、雙向綁定、內建指令、模板引用變數等等。

聊聊angular10中模板如何進行資料綁定?

綁定語法概覽

#綁定語法歸納起來大概有三種(基礎)

  • model => view (單向:插值、屬性綁定、樣式綁定)
  • view  => model(單向:事件綁定)
  • view <=> model(雙向:ngModule)

【相關教學推薦:《angular教學》】

#
<!-- model => view -->
{{expression}}
[target]="expression"
bind-target="expression"

<p> {{ msg }} </p>  // 插值表达式
<img [src]="heroImageUrl"> // 属性绑定
<app-hero-detail [hero]="currentHero"></app-hero-detail> // 组件通过属性绑定的方式传参
<div [ngClass]="{&#39;special&#39;: isSpecial}"></div> // 样式绑定
<div [class.special]="isSpecial">Special</div> // class绑定
<button [style.color]="isSpecial ? &#39;red&#39; : &#39;green&#39;"> // style绑定
<button [attr.aria-label]="help">help</button> // Attribute绑定

<!-- view  => model -->
(target)="statement"
on-target="statement"

<button (click)="onSave()">Save</button> // 元素事件
<app-hero-detail (deleteRequest)="deleteHero()"></app-hero-detail> // 组件事件,用于监听子组件传递过来的参数
<div (myClick)="clicked=$event" clickable>click me</div> // 指令事件

<!-- view <=> model -->
[(target)]="expression"
bindon-target="expression"

<input [(ngModel)]="name"> // 双向数据绑定
登入後複製

HTML attribute 與DOM property 的對比(很重要,加強理解)

理解HTML 屬性和DOM 屬性之間的區別,是了解Angular 綁定如何工作的關鍵。 Attribute 是由 HTML 定義的。 Property 是從 DOM(文件物件模型)節點存取的

  • 一些 HTML Attribute 可以 1:1 對應到 Property;例如,「 id」。
  • 某些 HTML Attribute 沒有對應的 Property。例如,aria-* colSpan rowSpan。
  • 某些 DOM Property 沒有對應的 Attribute。例如,textContent。

重要的是要記住,HTML Attribute 和 DOM Property 是不同的,就算它們有相同的名稱也是如此。在 Angular 中,HTML Attribute 的唯一作用是初始化元素和指令的狀態。

範本綁定使用的是 Property 和事件,而不是 Attribute。

在寫資料綁定時,你只是在和目標物件的 DOM Property 和事件打交道。

注意:

這個通用規則可以幫助你建立 HTML Attribute 和 DOM Property 的思考模型: 屬性負責初始化 DOM 屬性,然後完成。 Property 值可以改變;Attribute 值則不能。

此規則有一個例外。可以透過 setAttribute() 來變更 Attribute,接著它會重新初始化對應的 DOM 屬性。

案例1:input

<input type="text" value="Sarah">
登入後複製

當瀏覽器渲染input時,它會建立一個對應的DOM 節點,其value Property 已初始化為「Sarah 」。

當使用者在 input 中輸入 Sally 時,DOM 元素的 value Property 會變成 Sally。但是,如果使用 input.getAttribute('value') 查看 HTML 的 Attribute value,則可以看到該 attribute 保持不變 —— 它傳回了 Sarah。

HTML 的 value 這個 attribute 指定了初始值;DOM 的 value 就是這個 property 是目前值。

案例2:停用按鈕

disabled Attribute 是另一個範例。按鈕的 disabled Property 預設為 false,因此按鈕是啟用的。

當你加入 disabled Attribute 時,光是它的出現就將按鈕的 disabled Property 初始化成了 true,因此按鈕就停用了。

<button disabled>Test Button</button>
登入後複製

新增和刪除 disabled Attribute 會停用並啟用該按鈕。但是,Attribute 的值無關緊要,這就是為什麼你不能透過寫 仍被停用 來啟用此按鈕的原因。

要控制按鈕的狀態,請設定disabled Property,

<input [disabled]="condition ? true : false">
<input [attr.disabled]="condition ? &#39;disabled&#39; : null">
登入後複製

#範本/插值表達式{{}} (基礎,掌握)

模版中除了綁定變量,還能綁定方法

模版中還可以寫些簡單的邏輯,例如判斷或運算

import { Component } from &#39;@angular/core&#39;;
@Component({
  selector: &#39;app-root&#39;,
  template: `
      <p>变量绑定:{{ title }}</p>
      <p>方法绑定:{{ getVal }}</p>
      <p>方法绑定:{{ getVal2() }}</p>
      <p>简单运算 {{ 1 + 1 }}.</p>
      <p>简单运算 {{ price * 0.7 }}.</p>
      <p>简单运算:{{ gender === 0 ? &#39;男&#39;:&#39;女&#39; }}</p>
      <p>与方法结合 {{ price * 0.7 + getVal }}.</p>
      <p>与方法结合 {{ price * 0.7 + getVal2() }}.</p>
  `,
})
export class AppComponent {
  title = "模板绑定";
  price = 30;
  gender = 0;
  get getVal(): number { //es6新语法,函数可以当做变量来使用
    return 20;
  }
  getVal2(): number {
    return 33;
  }
}
登入後複製

當使用模板表達式時,請遵循下列指南:

  • 非常簡單
  • 執行迅速
  • 沒有可見的副作用(即模版中的邏輯不能改變元件的變數)

屬性綁定(基礎,掌握)

綁定圖片

import { Component } from &#39;@angular/core&#39;;
@Component({
  selector: &#39;app-root&#39;,
  template: `
    <img src="../assets/images/madao.jpg" alt="madao" />
    <img [src]="madaoSrc" alt="madao" /> // 推荐
    <img bind-src="madaoSrc" alt="madao" />
    `,
  styles: []
})
export class AppComponent {
  madaoSrc = &#39;../assets/images/madao.jpg&#39;;
}
登入後複製

綁定普通屬性

import { Component } from &#39;@angular/core&#39;;
@Component({
  selector: &#39;app-root&#39;,
  template: `
    <img [src]="user.pic" [alt]="user.name" />
    <table class="table-bordered">
      <tr>
        <th>name</th>
        <th>phone</th>
        <th>age</th>
      </tr>
      <tr>
        <td>张三</td>
        <td>13398490594</td>
        <td>33</td>
      </tr>
      <tr>
        <td [colSpan]="colSpan">李四</td> // 注意colSpan和colspan
        <td>15079049984</td>
        <td>22</td>
      </tr>
    </table>
    <button class="btn btn-primary" [disabled]="isDisabled">click</button>
    `,
  styles: []
})
export class AppComponent {
  madaoSrc = &#39;../assets/images/madao.jpg&#39;;
  user = {
   name: &#39;madao&#39;,
   pic: this.madaoSrc
  };
  colSpan = 2;
  isDisabled = false;
}
登入後複製

綁定自訂屬性

import { Component } from &#39;@angular/core&#39;;
@Component({
  selector: &#39;app-root&#39;,
  template: `
    <span [attr.data-title]="customTitle">一行文字</span>
    <span [attr.title]="customTitle">test title</span>
    <span [title]="customTitle">test title</span>
    `,
  styles: []
})
export class AppComponent {
  madaoSrc = &#39;../assets/images/madao.jpg&#39;;
  customTitle = &#39;bbb&#39;;
}
登入後複製

使用插值表達式(不建議)

插值也可以用於屬性,但常規做法還是用中括號[],建議整個項目保持風格統一

import { Component } from &#39;@angular/core&#39;;
@Component({
  selector: &#39;app-root&#39;,
  template: `
    <img src="{{ user.pic }}" alt="{{ user.name }}" />
    `,
  styles: []
})
export class AppComponent {
  madaoSrc = &#39;../assets/images/madao.jpg&#39;;
  user = {
    name: &#39;madao&#39;,
    pic: this.madaoSrc
  };
}
登入後複製

樣式綁定(屬於屬性綁定,基礎,掌握)

綁定單一樣式

import { Component } from &#39;@angular/core&#39;;
@Component({
  selector: &#39;app-root&#39;,
  template: `
      <button type="button" class="btn" [class.btn-primary]="theme === &#39;primary&#39;">Primary</button>
      <button type="button" class="btn" [class.btn-secondary]="true">secondary</button>
      <button type="button" class="btn" [class.btn-success]="isSuccess">success</button>
      <button type="button" class="btn" [class.btn-danger]="&#39;啦啦啦&#39;">danger</button>
      <button type="button" class="btn" [class.btn-danger]="0">danger</button>   //false
      <button type="button" class="btn" [class.btn-danger]="undefined">danger</button>  //false
    `,
  styles: []
})
export class AppComponent {
    theme = &#39;primary&#39;;
    isSuccess = true;
}
登入後複製

綁定多個class

import { Component } from &#39;@angular/core&#39;;
@Component({
  selector: &#39;app-root&#39;,
  template: `
      <button type="button" [class]="btnCls">btnCls</button>
      <button type="button" [class]="btnCls2">btnCls2</button>
      <button type="button" [class]="btnCls3">btnCls3</button>

      <!-- 也可以用内置指令ngClass -->
      <button type="button" [ngClass]="btnCls">btnCls</button>
      <button type="button" [ngClass]="btnCls2">btnCls2</button>
      <button type="button" [ngClass]="btnCls3">btnCls3</button>
    `,
  styles: []
})
export class AppComponent {
    btnCls = &#39;btn btn-primary&#39;;
    btnCls2 = [&#39;btn&#39;, &#39;btn-success&#39;];
    btnCls3 = {
      btn: true,
      &#39;btn-info&#39;: true
    };
}
登入後複製

綁定單一style

import { Component } from &#39;@angular/core&#39;;
@Component({
  selector: &#39;app-root&#39;,
  template: `
      <p [style.color]="&#39;#f60&#39;">一段文字</p>
      <p [style.height]="&#39;50px&#39;" [style.border]="&#39;1px solid&#39;">设置高度</p>
      <p [style.height.px]="50" [style.border]="&#39;1px solid&#39;">设置高度</p>
    `,
  styles: []
})
export class AppComponent {}
登入後複製

綁定多個style

import { Component } from &#39;@angular/core&#39;;
@Component({
  selector: &#39;app-root&#39;,
  template: `
      <p [style]="style1">style1</p>
      <p [style]="style2">style2</p>
      <p [style]="style3">style3</p>
      <!-- 也可以用内置指令ngStyle, 但不推荐,以后可能会弃用 -->
      <!--  <p [ngStyle]="style1">style1</p>-->
      <!--  <p [ngStyle]="style2">style2</p>-->

      <!-- ngStyle只接收对象 -->
      <p [ngStyle]="style3">style3</p>
    `,
  styles: []
})
export class AppComponent {
  style1 = &#39;width: 200px;height: 50px;text-align: center;border: 1px solid;&#39;;
  style2 = [&#39;width&#39;, &#39;200px&#39;, &#39;height&#39;, &#39;50px&#39;, &#39;text-align&#39;, &#39;center&#39;, &#39;border&#39;, &#39;1px solid&#39;]; // 有问题
  style3 = {
    width: &#39;200px&#39;,
    height: &#39;50px&#39;,
    &#39;text-align&#39;: &#39;center&#39;,
    border: &#39;1px solid&#39;
  };
}
登入後複製

綁定優先權

  • 某個類別或樣式綁定越具體,它的優先權就越高
  • 綁定總是優先於靜態屬性

#事件綁定(基礎,掌握)

#基本用法

import { Component } from &#39;@angular/core&#39;;
@Component({
  selector: &#39;app-root&#39;,
  template: `
      <button type="button" class="btn btn-primary" (click)="onClick()">Primary</button>
    `,
  styles: []
})
export class AppComponent {
    onClick() {
      console.log(&#39;onClick&#39;);
    } 
}
登入後複製

事件对象

$event 就是原生的事件对象

import { Component } from &#39;@angular/core&#39;;
@Component({
  selector: &#39;app-root&#39;,
  template: `
      <button type="button" class="btn btn-primary" (click)="onClick($event)">Primary</button>
    `,
  styles: []
})
export class AppComponent {
    onClick(event: MouseEvent) {
      console.log(&#39;onClick&#39;, event.target);
      //直接用event.target.value会报错,要用类型断言
      console.log((event.target as HTMLInputElement).value)
    }
}
登入後複製

事件捕获或事件冒泡

import { Component } from &#39;@angular/core&#39;;
@Component({
  selector: &#39;app-root&#39;,
  template: `
      <div style="width:200px;height:200px;background-color:red;" (click)="parentClick()">
      <!--<div style="width:100px;height:100px;background-color:blue;" (click)="chilrenClick($event)"></div>-->
      <div style="width:100px;height:100px;background-color:blue;" (click)="$event.stopPropagation()"></div> //可以在html使用一些简单的语法
    </div>
    `,
  styles: []
})
export class AppComponent {
  parentClick() {
    console.log(&#39;parentClick&#39;);
  }
  chilrenClick(event: MouseEvent) {
    event.stopPropagation();  //阻止事件冒泡
    console.log(&#39;chilrenClick&#39;);
  }
}
登入後複製

输入输出属性(主要是子传父,通过自定义事件)

输入属性

子组件

import { Component, Input } from &#39;@angular/core&#39;;
@Component({
  selector: &#39;app-root&#39;,
  template: `<p>
               Today&#39;s item: {{item}}
             </p>`
})
export class ItemDetailComponent  {
  @Input() item: string;
}
登入後複製
登入後複製

父组件

import { Component } from &#39;@angular/core&#39;;
@Component({
  selector: &#39;app-root&#39;,
  template: `
     <app-item-detail [item]="currentItem"></app-item-detail>
  `,
})
export class AppComponent {
  currentItem = &#39;Television&#39;;
}
登入後複製
登入後複製

输出属性

  • 通过 new EventEmitter() 自定义一个事件;
  • 调用 EventEmitter.emit(data) 发出事件,传入数据;
  • 父指令通过监听自定义事件,并通过传入的 $event 对象接收数据。

子组件

import { Component, Output, EventEmitter } from &#39;@angular/core&#39;;
@Component({
  selector: &#39;app-root&#39;,
  template: `<label>Add an item: <input #newItem></label>
             <button (click)="addNewItem(newItem.value)">Add to parent&#39;s list</button>`,
})
export class ItemOutputComponent {
  @Output() newItemEvent = new EventEmitter<string>(); //子传父,输出属性
  addNewItem(value: string) {
    this.newItemEvent.emit(value); //自定义事件触发
  }
}
登入後複製

父组件

import { Component } from &#39;@angular/core&#39;;
@Component({
  selector: &#39;app-root&#39;,
  template: `
     <app-item-output (newItemEvent)="addItem($event)"></app-item-output> //监听自定义事件
  `,
})
export class AppComponent {
   items = [&#39;item1&#39;, &#39;item2&#39;, &#39;item3&#39;, &#39;item4&#39;];
    addItem(newItem: string) {
      this.items.push(newItem);
    }
}
登入後複製

在元数据中声明输入和输出属性

固然可以在 @Directive 和 @Component 元数据中声明 inputs 和 outputs,但不推荐提供别名

@Input()和@Output()可以接收一个参数,作为变量的别名,那么父组件中只能用别名绑定

子组件

import { Component, Input, EventEmitter, Output } from &#39;@angular/core&#39;;
@Component({
  selector: &#39;app-root&#39;,
  template: `<p>
               Today&#39;s item: {{item}}
             </p>`
})
export class ItemDetailComponent  {
  @Input(&#39;aliasItem&#39;) item: string; 
  @Output(&#39;newItem&#39;) newItemEvent = new EventEmitter<string>();
  
  addNewItem(value: string) {
     this.newItemEvent.emit(value);
   }
}
登入後複製

父组件

import { Component } from &#39;@angular/core&#39;;
@Component({
  selector: &#39;app-root&#39;,
  template: `
     <app-item-detail [aliasItem]="currentItem" //注意是绑定的别名
     (newItem)="addItem($event)"></app-item-detail> //注意是监听的别名
  `,
})
export class AppComponent {
  currentItem = &#39;Television&#39;;
  items = [&#39;item1&#39;, &#39;item2&#39;, &#39;item3&#39;, &#39;item4&#39;];
  addItem(newItem: string) {
    this.items.push(newItem);
  }
}
登入後複製

输入属性一定要用中括号[]绑定?

如果绑定的值是静态的,就不需要[];为了统一风格尽量用上[]

import { Component } from &#39;@angular/core&#39;;
@Component({
  selector: &#39;app-root&#39;,
  template: `
     <app-item-detail item="static item"></app-item-detail>
  `,
})
export class AppComponent {
  // currentItem = &#39;Television&#39;;
}
登入後複製
登入後複製

双向绑定(基础,掌握)

先决条件

  • 组件的属性绑定
  • 组件的事件绑定
  • 输入和输出(父子组件通信)

基本的双向绑定

子组件

import {Component, OnInit, ChangeDetectionStrategy, EventEmitter, Input, Output} from &#39;@angular/core&#39;;@Component({  selector: &#39;app-sizer&#39;,  template: `
    <div>
      <button class="btn btn-danger" (click)="dec()" title="smaller">-</button>
      <button class="btn btn-primary" (click)="inc()" title="bigger">+</button>
      <label [style.font-size.px]="size">FontSize: {{size}}px</label>
    </div>
  `,  styles: [
  ],  changeDetection: ChangeDetectionStrategy.OnPush
})export class SizerComponent implements OnInit {  @Input()  size: number | string;  
  // 想要用双向绑定语法,output变量名就一定是输入属性名加上Change  @Output() sizeChange = new EventEmitter<number>();  constructor() { }

  ngOnInit(): void {
  }  dec() { this.resize(-1); }  inc() { this.resize(+1); }  resize(delta: number) {    this.size = Math.min(40, Math.max(8, +this.size + delta));    this.sizeChange.emit(this.size);
  }
}
登入後複製

父组件

import { Component } from &#39;@angular/core&#39;;@Component({  selector: &#39;app-root&#39;,  template: `
     <app-sizer [(size)]="fontSizePx"></app-sizer>
     <div [style.font-size.px]="fontSizePx">Resizable Text</div>
  `,
})export class AppComponent {
    fontSizePx = 16;
}
登入後複製

双向绑定工作原理

为了使双向数据绑定有效,@Output() 属性的名字必须遵循 inputChange 模式,其中 input 是相应 @Input() 属性的名字。例如,如果 @Input() 属性为 size ,则 @Output() 属性必须为 sizeChange 。

上面的 sizerComponent 具有值属性 size 和事件属性 sizeChange。 size 属性是 @Input(),因此数据可以流入 sizerComponent 。 sizeChange 事件是一个 @Output() ,它允许数据从 sizerComponent 流出到父组件。

上面例子,有两个方法, dec() 用于减小字体大小, inc() 用于增大字体大小。这两种方法使用 resize() 在最小/最大值的约束内更改 size 属性的值,并发出带有新 size 值的事件。

简写形式

双向绑定语法是属性绑定和事件绑定的组合的简写形式

<app-sizer [size]="fontSizePx" (sizeChange)="fontSizePx=$event"></app-sizer>
登入後複製

表单中的双向绑定

因为没有任何原生 HTML 元素遵循了 x 值和 xChange 事件的命名模式,所以与表单元素进行双向绑定需要使用 NgModel

基本使用

根据之前基本的双向绑定知识,[(ngModel)]语法可拆解为:

  • 名为ngModel的输入属性
  • 名为ngModelChange的输出属性

使用[(ngModule)]双向绑定的前提条件是在模块中引入FormsModule

import {Component} from &#39;@angular/core&#39;;

@Component({
  selector: &#39;example-app&#39;,
  template: `
    <input [(ngModel)]="name" #ctrl="ngModel" required>
    
    <p>Value: {{ name }}</p>
    <p>Valid: {{ ctrl.valid }}</p>
    
    <button (click)="setValue()">Set value</button>
  `,
})
export class SimpleNgModelComp {
  name: string = &#39;&#39;;

  setValue() {
    this.name = &#39;Nancy&#39;;
  }
}
登入後複製
<input [(ngModel)]="name" />
上面这行代码相当于:
<input [value]="name" (input)="name = $event.target.value" />
登入後複製

在表单中的使用

表单中使用[(ngModel)],需要做下面两件事的其中之一

  • 给控件加上name属性
  • 将ngModelOptions.standalone设为true
<form>
    <input [(ngModel)]="value" name="name" />
    <input [(ngModel)]="value" [ngModelOptions]="{ standalone: true }" />
</form>
登入後複製

注意:表单中使用双向数据绑定,知识点比较多,这里只做简单了解,后续会出专门章节探讨

内置指令

循环指令 *ngFor (非常基础,掌握)

arr:string[] = [&#39;张三&#39;,&#39;李四&#39;,&#39;王五&#39;]; 
trackByItems(index: number, item: Item): number { return item.id; }

<div *ngFor="let item of arr; let i=index" (click)=&#39;choseThis(item,i)&#39;>
   索引值:{{i}} -- 内容:{{item}}
</div>

//trackBy一般和长列表一起使用,减少dom替换次数,提升性能
<div *ngFor="let item of items; trackBy: trackByItems">
  ({{item.id}}) {{item.name}}
</div>
登入後複製

条件渲染 *ngIf ngStyle ngClass ngSwitch(非常基础)

isShow: Boolean = true;
personState: number = 2;

//频繁切换不建议用,频繁加载和移除有较高的性能消耗 (重要)
<p *ngIf="isShow">命令模式</p> // 不频繁切换推荐用
<p [hidden]="isShow">命令模式</p> // 频繁切换推荐用


currentStyles = {
      &#39;font-style&#39;:  this.canSave      ? &#39;italic&#39; : &#39;normal&#39;,
      &#39;font-weight&#39;: !this.isUnchanged ? &#39;bold&#39;   : &#39;normal&#39;,
      &#39;font-size&#39;:   this.isSpecial    ? &#39;24px&#39;   : &#39;12px&#39;
};
<div [ngClass]="isSpecial ? &#39;special&#39; : &#39;&#39;">ngClass</div>
<div [ngStyle]="currentStyles">
  ngStyle
</div>

// 使用样式有2种(style.dispaly 和 class.hidden)
<p [style.display]="isShow?&#39;block&#39;:&#39;none&#39;">style模式</p> //频繁切换建议用样式
<p [class.hidden]="isShow">class模式</p>


//匹配多种情况的条件渲染,跟vue的v-if/v-else-if/v-else类似
//适合多种状态,显示一种的情况
<div [ngSwitch] = &#39;personState&#39;>
    <div *ngSwitchCase="1">工作</div>
    <div *ngSwitchCase="2">吃饭</div>
    <div *ngSwitchDefault>睡觉</div>
</div>
登入後複製

双向数据绑定指令 [(ngModel)]

//Angular不能直接识别ngModel,需要通过引入模块FormsModule来访问
import {FormsModule} from &#39;@angular/forms&#39;;
imports: [FormsModule]

public name = "张三";
<input [(ngModel)] = "name" type="text"> //人工绑定,更好的做法是通过响应式表单绑定
<input bindon-change="name" type="text"> //备选

//属性绑定+事件绑定 = ngModel (重要)
<input [value]="name" (input)="name=$event.target.value" >
登入後複製

模板引用变量

基本使用

使用井号(#)声明模板引用变量,可以获取DOM 元素、指令、组件、TemplateRef 或 Web Component。

import {Component} from &#39;@angular/core&#39;;
@Component({
  selector: &#39;app-tpl-var&#39;,
  template: `
    <input #phone placeholder="phone number" />
    <button (click)="callPhone(phone.value)">Call</button>
  `,
})
export class TplVarComponent {
  constructor() { }
  callPhone(value: string) {
    console.log(&#39;callPhone&#39;, value);
  }
}
登入後複製

ref

还有种写法就是ref, 下面两种写法是一样的

<input #fax placeholder="fax number" />

<input ref-fax placeholder="fax number" />
登入後複製

引用组件

在组件章节,介绍了获取子组件的属性和方法,有两种方法:本地变量和@viewChild()

import {Component} from &#39;@angular/core&#39;;
@Component({
  selector: &#39;app-tpl-var&#39;,
  template: `
    <div class="demo-sec">
      <button class="btn btn-primary" (click)="sizer.inc()">app inc</button>
      <app-sizer [(size)]="size" #sizer></app-sizer>
      size: {{ size }}
    </div>
  `,
})
export class TplVarComponent {
  size = 16;
  constructor() { }
}
登入後複製

输入和输出

输入属性

子组件

import { Component, Input } from &#39;@angular/core&#39;;
@Component({
  selector: &#39;app-root&#39;,
  template: `<p>
               Today&#39;s item: {{item}}
             </p>`
})
export class ItemDetailComponent  {
  @Input() item: string;
}
登入後複製
登入後複製

父组件

import { Component } from &#39;@angular/core&#39;;
@Component({
  selector: &#39;app-root&#39;,
  template: `
     <app-item-detail [item]="currentItem"></app-item-detail>
  `,
})
export class AppComponent {
  currentItem = &#39;Television&#39;;
}
登入後複製
登入後複製

输出属性

子组件

import { Component, Output, EventEmitter } from &#39;@angular/core&#39;;
@Component({
  selector: &#39;app-root&#39;,
  template: `<label>Add an item: <input #newItem></label>
             <button (click)="addNewItem(newItem.value)">Add to parent&#39;s list</button>`,
})
export class ItemOutputComponent {
  @Output() newItemEvent = new EventEmitter<string>();
  addNewItem(value: string) {
    this.newItemEvent.emit(value);
  }
}
登入後複製

父组件

import { Component } from &#39;@angular/core&#39;;
@Component({
  selector: &#39;app-root&#39;,
  template: `
     <app-item-output (newItemEvent)="addItem($event)"></app-item-output>
  `,
})
export class AppComponent {
   items = [&#39;item1&#39;, &#39;item2&#39;, &#39;item3&#39;, &#39;item4&#39;];
    addItem(newItem: string) {
      this.items.push(newItem);
    }
}
登入後複製

在元数据中声明输入和输出属性

固然可以在 @Directive 和 @Component 元数据中声明 inputs 和 outputs, 不推荐提供别名。

@Input()和@Output()可以接收一个参数,作为变量的别名,那么父组件中只能用别名绑定 子组件

import { Component, Input, EventEmitter, Output } from &#39;@angular/core&#39;;
@Component({
  selector: &#39;app-root&#39;,
  template: `<p>
               Today&#39;s item: {{item}}
             </p>`
})
export class ItemDetailComponent  {
  @Input(&#39;aliasItem&#39;) item: string; // decorate the property with @Input()
  @Output(&#39;newItem&#39;) newItemEvent = new EventEmitter<string>();
  addNewItem(value: string) {
     this.newItemEvent.emit(value);
   }
}
登入後複製

父组件

import { Component } from &#39;@angular/core&#39;;
@Component({
  selector: &#39;app-root&#39;,
  template: `
     <app-item-detail [aliasItem]="currentItem" (newItem)="addItem($event)"></app-item-detail>
  `,
})
export class AppComponent {
  currentItem = &#39;Television&#39;;
  items = [&#39;item1&#39;, &#39;item2&#39;, &#39;item3&#39;, &#39;item4&#39;];
  addItem(newItem: string) {
    this.items.push(newItem);
  }
}
登入後複製

输入属性一定要用中括号[]绑定?

如果绑定的值是静态的,就不需要[]

import { Component } from &#39;@angular/core&#39;;
@Component({
  selector: &#39;app-root&#39;,
  template: `
     <app-item-detail item="static item"></app-item-detail>
  `,
})
export class AppComponent {
  // currentItem = &#39;Television&#39;;
}
登入後複製
登入後複製

管道(基础,掌握)

常用的管道

1、大小写字母转换

str = &#39;Hello&#39;;
str1 = &#39;World&#39;;
<p>{{str | uppercase}}-{{str1 | lowercase}} </p>  //str:hello str1:WORLD
登入後複製

2、 日期格式化(经常使用)

today = new Date();

<p>现在的时间是{{today | date:&#39;yyyy-MM-dd HH:mm:ss&#39;}}</p>
登入後複製

3、保留小数后面多少位 下面例子的含义是,3表示最少几位整数,后面的2-4表示最少最少2位小数,最多4位小数,不足补零,小数会四舍五入。

num = 125.156896;

<p>num保留4位小数的值是:{{num | number:&#39;3.2-4&#39;}}</p> //125.1569
登入後複製

4、货币转换

count = 5;
price = 1.5;

<p>数量:{{count}}</p> // 数据:5
<p>价格:{{price}}</p> // 价格:1.5
<p>总价:{{(price * count) | currency:&#39;¥&#39;}}</p> // 价格:¥7.5
登入後複製

5、字符串截取

name = &#39;只对你说&#39;;

<p>{{name | slice : 2 : 4}}</p> // 你说
登入後複製

6、json格式化(有时需要看一下数据)

 <p>{{ { name: &#39;semlinker&#39; } | json }}</p> // { "name": "semlinker" }
登入後複製

自定义管道

1、创建管道文件

ng g pipe /piper/mypiper
登入後複製

2、在管道文件中写自己的逻辑transform两个参数分别表示传入值和参数

import { Pipe, PipeTransform } from &#39;@angular/core&#39;;

@Pipe({
  name: &#39;multiple&#39;
})
export class MypiperPipe implements PipeTransform {
  transform(value: any, args?: any): any {
    //value:输入值 args:参数
    if(!args){//无参的情况下
      args = 1;
    }
    return value*args;
  }
}
登入後複製

注意:通过命令行生成的管道(过滤器),会自动在全局声明; 管道传入的参数是在':'冒号后面表示

更多编程相关知识,请访问:编程视频!!

以上是聊聊angular10中模板如何進行資料綁定?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
4 週前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
4 週前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
4 週前 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解鎖Myrise中的所有內容
1 個月前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

如何在Ubuntu 24.04上安裝Angular 如何在Ubuntu 24.04上安裝Angular Mar 23, 2024 pm 12:20 PM

Angular.js是一種可自由存取的JavaScript平台,用於建立動態應用程式。它允許您透過擴展HTML的語法作為模板語言,以快速、清晰地表示應用程式的各個方面。 Angular.js提供了一系列工具,可協助您編寫、更新和測試程式碼。此外,它還提供了許多功能,如路由和表單管理。本指南將討論在Ubuntu24上安裝Angular的方法。首先,您需要安裝Node.js。 Node.js是一個基於ChromeV8引擎的JavaScript運行環境,可讓您在伺服器端執行JavaScript程式碼。要在Ub

淺析angular中怎麼使用monaco-editor 淺析angular中怎麼使用monaco-editor Oct 17, 2022 pm 08:04 PM

angular中怎麼使用monaco-editor?以下這篇文章記錄下最近的一次業務中用到的 m​​onaco-editor 在 angular 中的使用,希望對大家有幫助!

一文探究Angular中的服務端渲染(SSR) 一文探究Angular中的服務端渲染(SSR) Dec 27, 2022 pm 07:24 PM

你知道 Angular Universal 嗎?可以幫助網站提供更好的 SEO 支援哦!

如何使用PHP和Angular進行前端開發 如何使用PHP和Angular進行前端開發 May 11, 2023 pm 04:04 PM

隨著網路的快速發展,前端開發技術也不斷改進與迭代。 PHP和Angular是兩種廣泛應用於前端開發的技術。 PHP是一種伺服器端腳本語言,可以處理表單、產生動態頁面和管理存取權限等任務。而Angular是一種JavaScript的框架,可以用來開發單一頁面應用程式和建構元件化的網頁應用程式。本篇文章將介紹如何使用PHP和Angular進行前端開發,以及如何將它們

Angular元件及其顯示屬性:了解非block預設值 Angular元件及其顯示屬性:了解非block預設值 Mar 15, 2024 pm 04:51 PM

Angular框架中元件的預設顯示行為不是區塊級元素。這種設計選擇促進了元件樣式的封裝,並鼓勵開發人員有意識地定義每個元件的顯示方式。透過明確設定CSS屬性 display,Angular組件的顯示可以完全控制,從而實現所需的佈局和響應能力。

聊聊自訂angular-datetime-picker格式的方法 聊聊自訂angular-datetime-picker格式的方法 Sep 08, 2022 pm 08:29 PM

怎麼自訂angular-datetime-picker格式?以下這篇文章聊聊自訂格式的方法,希望對大家有幫助!

PHP電子郵件範本:客製化和個人化您的郵件內容。 PHP電子郵件範本:客製化和個人化您的郵件內容。 Sep 19, 2023 pm 01:21 PM

PHP電子郵件範本:客製化和個人化您的郵件內容隨著電子郵件的普及和廣泛應用,傳統的郵件範本已經無法滿足人們對個人化和客製化郵件內容的需求。現在,我們可以透過使用PHP程式語言來創建客製化和個人化的電子郵件範本。本文將為您介紹如何使用PHP來實現這一目標,並提供一些具體的程式碼範例。一、建立郵件範本首先,我們需要建立一個基本的郵件範本。這個模板可以是一個HTM

PPT蒙版該怎麼添加 PPT蒙版該怎麼添加 Mar 20, 2024 pm 12:28 PM

關於PPT蒙版,很多人肯定對它很陌生,一般人做PPT不會將牠吃透,而是湊活著可以做出來自己喜歡的就行,所以很多人都不知道PPT蒙版到底是什麼意思,也不知道這個蒙版有什麼作用,甚至更不知道它可以讓圖片變得不再那麼單調,想要學習的小伙伴們快來了學習學習,為你的PPT圖片上添上點吧PPT蒙版吧,讓它不再單調了。那麼,PPT蒙版該怎麼添呢?請往下看。 1.首先我們開啟PPT,選擇一張空白的圖片,之後右鍵點選【設定背景格式】,純色選擇顏色就行。 2.點選【插入】,藝術字,輸入字3.點選【插入】,點選【形狀】

See all articles