# Day06 【牙起來】 繫結1 內嵌綁定 - 程式面介紹 接下來要切換到程式面來看看,就是Typescript! ## 綁定成員(變數) - Binding 打開 `role.component.ts` 檔案 在程式的class內新增一個 **變數**: 血量`hp` > 其實在這使用 **變數 variable** 稱呼其實不準確,正確來說是物件底下的 **成員 member** > 後面講到Typescript章節時會重新提及,在此請先忽略 ```typescript= import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-role', templateUrl: './role.component.html', styleUrls: ['./role.component.css'] }) export class RoleComponent implements OnInit { hp = 5; constructor() { } ngOnInit(): void { } } ```  ### 內嵌繫結 Interpolation Binding `內嵌`或稱`插值`,在樣板上透過兩個大括號 `{{}}` 來顯示出此變數 把變數(成員)當前的數值,從**Typescript**中顯示到**HTML**畫面上 修改 `role.component.html` ```html= <h2>角色區塊</h2> <div>血量: {{hp}}</div> ``` 完成畫面,血量出來了!  只有血量還不夠,還必須要有一個酷炫的名字 修改 `role.component.ts` ```typescript= ... export class RoleComponent implements OnInit { hp = 5; name = '初心冒險者'; constructor() { } ngOnInit(): void { } } ``` 接著修改 `role.component.html` ```html= <h2>角色區塊</h2> <div>名稱: {{name}}</div> <div>血量: {{hp}}</div> ``` 完成畫面  ### 數字會動的變數 修改 `role.component.ts`,在 **ngOnInit()** 裡加入 **setInterval function** ```typescript= export class RoleComponent implements OnInit { hp = 5; name = '初心冒險者'; constructor() { } ngOnInit(): void { setInterval(() => { this.hp += 1; }, 1000) } } ``` 血量會隨著秒數每秒增加! 可以看出Angular綁定變數,畫面及時的渲染、顯示最新的值出來 而非死的一坨在那一動也不動 > 恭喜到這一步,已經學成**40%的Angular**!
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up