內嵌繫結
app.component.ts中設定屬性變數
1 2 3 4 5
| export class AppComponent { title = 'My Website'; link = '前往Google'; url = 'https://google.com'; }
|
app.component.html 檔案內使用雙括號將變數宣染
{{}}
繃定
1 2 3 4
| <div class="container my-5"> <h1>{{title}}</h1> <a href="{{url}}">{{link}}</a> </div>
|

app.component.ts中設定屬性變數
1 2 3 4
| export class AppComponent { a = 10; b = 50; }
|
app.component.html 檔案內直接在樣板做運算
{{算數}}
繃定
屬性繫結 property binding
[property] = ‘statement’
app.component.html 檔案內
a標籤 [routerLink] 必須引入RouterLink 在 from ‘@angular/router’
[欄位參數]
繫結
1 2 3 4
| <div class="container my-5"> <h1>標題</h1> <a [routerLink]="欄位參數">Google連結</a> </div>
|
Class動態樣式 [ngClass] 綁定方是等於布林值是或否 ? ‘active’ : ‘’”
綁定自定義的attribute?
app.component.html 檔案內
[attr.data-title]
繫結
1
| <h1 [attr.data-title]=title>標題</h1>
|
事件繫結 event binding
app.component.html 檔案內
(click)
事件繫結函式
1 2 3 4
| <div class="container my-5"> <input type="button" value="更換標題" (click)="changeTitle()"> <h1>{{title}}</h1> </div>
|
app.component.ts中設定屬性變數
點擊函式改變title
1 2 3 4 5 6
| export class AppComponent { title = 'My Website'; changeTitle(){ this.title = '更換後的標題'; } }
|
傳入事件參數$event
app.component.html 檔案內
點擊函式傳入參數$event
1 2 3 4 5 6
| <div class="container my-5"> <input type="button" value="更換標題" (click)="changeTest($event)"> <h1>{{title}}</h1> </div>
|
app.component.ts中設定屬性變數
1 2 3 4 5 6 7
| export class AppComponent { title = 'My Website'; changeTest($event: any) { console.log($event) this.title = 'Lara換後的標題'; } }
|
雙向繫結 two-way binding
[(ngModel)] = ‘property’
雙向繫結能同時做到屬性繫結()以及事件繫結[],所以符號是[()]用他來繫結某個property
app.component.html 檔案內
表單[()] 綁定
1 2 3
| <input type="text" value="" placeholder="請輸入點什麼吧" [(ngModel)]="text"> <p>您的輸入: <span>{{text}}</span></p> <p>字數: <span>{{text.length}}</span></p>
|
app.component.ts中設定屬性變數
1 2 3 4 5 6 7 8 9 10 11 12 13
| import { Component } from '@angular/core'; + import { FormsModule } from '@angular/forms'; @Component({ selector: 'app-root', imports: [ + FormsModule ], templateUrl: './app.component.html', styleUrl: './app.component.scss' }) export class AppComponent { + text="text" }
|