# Angular - 組件與插值與屬性綁定 在進入開始撰寫 Angular 邏輯前,首要先了解一下,Angular 中的組件,以及內嵌綁定與屬性綁定。 ## Angular 的文件命名與組件 ### 文件命名方式 使用 `ng new` 指令,在 terminal 中 new 出一個 angular 的檔案夾後,我們會在 src 的 app 資料夾中看見一個名為 `app.component.ts`的文件,在 Angular 中,文件的命名方式是以 `feature.type.**`,feature表示特性,type表示類型。 舉例來說: - 導覽列組件的主要組件架構是 `navbar.component.ts` - 組件相關的 html 可以寫成`navbar.component.html` - 如果是 module 就會寫成 `navbar.module.ts` 以上都可以在 src 的 app 資料夾中好好的研究一下! ![](https://hackmd.io/_uploads/r1xsw3iEh.png) ### Component 組件文件裡面有什麼? "一個元件控制著一塊被稱為檢視的螢幕區域。它由一個 TypeScript 類、一個 HTML 範本和一個 CSS 樣式表組成。 TypeScript 類定義了 HTML 範本和渲染的 DOM 結構的互動,而樣式表描述了它的外觀。" - 取自 Angular 官方 首先,我們需要先從 @angular/core 導入 component,才能使**組件與樣板之間產生連結**。 前面有提到, Angular 是基於 MVC 設計模式建構的框架,並且組件主要是用來控制 UI 的,所以在這份文件中,可以很清楚的看到,我們使用了 `@component` 的裝飾器,來連結 html 以及 css,並且,再 component 的類中撰寫互動邏輯,透過 `data binding` 方式來與 template 做畫面的互動。 ![angular-component](https://hackmd.io/_uploads/Sy3tK2oE2.png) ## 何謂 data binding? "Data binding automatically keeps your page up-to-date based on your application's state. You use data binding to specify things such as the source of an image, the state of a button, or data for a particular user." - 取自 angular 官方 資料綁定的目的就是為了使畫面與使用者產生互動,使頁面可以呼應資料,並且保持在最新的狀態。 而在 Angular 中的資料綁定又可以分為四種: - 內嵌綁定/插值 - Interpolation - 屬性綁定 - property binding - 事件綁定 - event binding - 雙向綁定 - two way binding ![data binding](https://hackmd.io/_uploads/HknAsR6E2.png) 在這篇文章將會先介紹兩個最基本的資料綁定類型: #### 內嵌綁定/插值 - Interpolation 這可以說是最直接的資料綁定方式,**屬於單向性綁定** 在 `app.component.html` 中,使用雙大括號寫成 `{{值}}` ``` // 這個文件是 app.component.html <div> <h1>{{title}}<h1> // 這裡使用 {{title}} 的方式獲取在 app 組件中的 title 值 <div> // 這個文件是 app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], }) export class AppComponent { title:string = 'intro'; // 一但 title 的值有改變,那就會連帶的影響畫面的呈現(連帶影響 html ) } ``` #### 屬性綁定 - Property Binding 屬性綁定又比插值具有更多的彈性使用,**屬於單向性綁定** 在`app.component.html` 中,使用`[屬性]="值"` ``` // 這個文件是 app.component.html <div> <h1 [innerHtml]="title"><h1> <button [disable]="isAble">click<button> // 在此會去連結到組件中的 isAble 值,來判斷按鈕是否會被觸發,若組件改為 true,則按鈕無法點擊 <div> // 這個文件是 app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], }) export class AppComponent { title:string = 'title'; // 一但 title 的值有改變,就會連帶影響在 html 中 h1 的屬性值 isAble:boolean = false; // 一但 isAble 的值有改變,就會連帶影響在 html 中 button 的屬性值 } ``` ###### tags: `Angular`