Angular 新手入門

現在該看一下 Google 的 Angular 框架了,這是另一個你經常會遇到的前端框架。在本文中,我們將會探索 Angular 所提供的功能、安裝必備工具、建立範例應用程式,並進一步瞭解 Angular 的基本架構。

預備知識: 熟悉基本的 HTMLCSSJavaScript 程式語言,具備 終端機/命令列環境 基本知識。
學習目標: 設立本機的 Angular 開發環境,建立初始應用程式,瞭解 Angular 基本運作方式。

什麼是 Angular?

Angular 是一個基於 TypeScript 的開發平台。身為一個平台,Angular 包含:

  • 一個元件化的框架,用來建構可延展的 Web 應用程式。
  • 一整套完美整合的函式庫,包含各種不同的功能,包含路由機制、表單管理、Client/Server 通訊,以及更多。
  • 一組完善的開發工具,幫助你開發、建置、測試、更新你的程式碼。

When you build applications with Angular, you're taking advantage of a platform that can scale from single-developer projects to enterprise-level applications. Angular is designed to make updating as easy as possible, so you can take advantage of the latest developments with a minimum of effort. Best of all, the Angular ecosystem consists of a diverse group of over 1.7 million developers, library authors, and content creators.

Before you start exploring the Angular platform, you should know about the Angular CLI. The Angular CLI is the fastest, easiest, and recommended way to develop Angular applications. The Angular CLI makes a number of tasks easy. Here are some examples:

ng build Compiles an Angular app into an output directory.
ng serve Builds and serves your application, rebuilding on file changes.
ng generate Generates or modifies files based on a schematic.
ng test Runs unit tests on a given project.
ng e2e Builds and serves an Angular application, then runs end-to-end tests.

You'll find the Angular CLI to be a valuable tool for building out your applications.

What you'll build

This tutorial series guides you through building a to-do list application. Via this application you'll learn how to use Angular to manage, edit, add, delete, and filter items.

Prerequisites

To install Angular on your local system, you need the following:

  • Node.js

    Angular requires a current, active LTS, or maintenance LTS version of Node.js. For information about specific version requirements, see the engines key in the package.json file.

    For more information on installing Node.js, see nodejs.org. If you are unsure what version of Node.js runs on your system, run node -v in a terminal window.

  • npm package manager

    Angular, the Angular CLI, and Angular applications depend on npm packages for many features and functions. To download and install npm packages, you need an npm package manager. This guide uses the npm client command line interface, which is installed with Node.js by default. To check that you have the npm client installed, run npm -v in a terminal window.

設置你的應用程式

你可以在終端機裡透過使用 Angular 命令列介面( CLI )來產生、建置、測試和佈署 Angular 應用程式。請在終端機裡執行以下指令來安裝 Angular 命令列介面:

npm install -g @angular/cli

Angular 命令列介面的指令全都是以 ng 開頭,後面接著你想要執行的 CLI 指令。進入桌面資料夾裡,使用 ng new 指令來建立一個名為 todo 的新應用程式:

ng new todo --routing=false --style=css

這個 ng new 指令在你的桌面建立了一個最簡單的初始 Angular 應用程式。指令後面接著的 --routing--style 參數,用於定義應用程式如何處理導覽及樣式。這個教學描述了更多有關這個功能的細節。

如果出現是否啟用強制型別檢查的提示,你可以選擇「是」。

使用 cd 指令進入你新建的專案:

cd todo

使用 ng serve 執行你的 todo 應用程式

ng serve

當命令列提示你是否共享用於分析的資料時,請回答 no

在瀏覽器開啟 http://localhost:4200/ 來檢視你新建的應用程式。應用程式會即時重新整理以便反應你對原始碼的異動。

ng serve 正在執行時,你可能需要開啟第二個終端機分頁或視窗來執行指令。任何時間點想要停止應用程式,請在終端機輸入 Ctrl+c

Get familiar with your Angular application

The application source files that this tutorial focuses on are in src/app. Key files that the CLI generates automatically include the following:

  1. app.module.ts: Specifies the files that the application uses. This file acts as a central hub for the other files in your application.
  2. app.component.ts: Also known as the class, contains the logic for the application's main page.
  3. app.component.html: Contains the HTML for AppComponent. The contents of this file are also known as the template. The template determines the view or what you see in the browser.
  4. app.component.css: Contains the styles for AppComponent. You use this file when you want to define styles that only apply to a specific component, as opposed to your application overall.

A component in Angular is made up of three main parts—the template, styles, and the class. For example, app.component.ts, app.component.html, and app.component.css together constitute the AppComponent. This structure separates the logic, view, and styles so that the application is more maintainable and scalable.

In this way, you are using the best practices from the very beginning.

The Angular CLI also generates a file for component testing called app.component.spec.ts, but this tutorial doesn't go into testing, so you can ignore that file.

Whenever you generate a component, the CLI creates these four files in a directory with the name you specify.

The structure of an Angular application

Angular is built with TypeScript. TypeScript is a superset of JavaScript meaning that any valid JavaScript is valid TypeScript. TypeScript offers typing and a more concise syntax than plain JavaScript, which gives you a tool for creating more maintainable code and minimizing bugs.

Components are the building blocks of an Angular application. A component includes a TypeScript class that has a @Component() decorator, an HTML template, and styles.

The class

The class is where you put any logic your component needs. This code can include functions, event listeners, properties, and references to services to name a few. The class is in a file with a name such as feature.component.ts, where feature is the name of your component. So, you could have files with names such as header.component.ts, signup.component.ts, or feed.component.ts. You create a component with a @Component() decorator that has metadata that tells Angular where to find the HTML and CSS. A typical component is as follows:

import { Component } from '@angular/core';

@Component({
  selector: 'app-item',
    // the following metadata specifies the location of the other parts of the component
  templateUrl: './item.component.html',
  styleUrls: ['./item.component.css']
})

export class ItemComponent {
// your code goes here
}

This component is called ItemComponent, and its selector is app-item. You use a selector just like regular HTML tags by placing it within other templates. When a selector is in a template, the browser renders the template of that component. This tutorial guides you through creating two components and using one within the other.

Angular's component model offers strong encapsulation and an intuitive application structure. Components also make your application easier to unit test and can improve the overall readability of your code.

The HTML template

Every component has an HTML template that declares how that component renders. You can define this template either inline or by file path.

To refer to an external HTML file, use the templateUrl property:

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})

export class AppComponent {
}

To write inline HTML, use the template property and write your HTML within backticks:

@Component({
  selector: 'app-root',
  template: `<h1>Hi!</h1>`,
})

export class AppComponent {
}

Angular extends HTML with additional syntax that lets you insert dynamic values from your component. Angular automatically updates the rendered DOM when your component’s state changes. One use of this feature is inserting dynamic text, as shown in the following example.

<h1>{{ title }}</h1>

The double curly braces instruct Angular to interpolate the contents within them. The value for title comes from the component class:

import { Component } from '@angular/core';

@Component ({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
    title = 'To do application';
}

When the application loads the component and its template, the browser sees the following:

<h1>To do application</h1>

Styles

A component can inherit global styles from the application's styles.css file and augment or override them with its own styles. You can write component-specific styles directly in the @Component() decorator or specify the path to a CSS file.

To include the styles directly in the component decorator, use the styles property:

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styles: ['h1 { color: red; }']
})

Typically, a component uses styles in a separate file using the styleUrls property:

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

With component-specific styles, you can organize your CSS so that it is easily maintainable and portable.

Summary

That's it for your first introduction to Angular. At this point you should be set up and ready to build an Angular app, and have a basic understanding of how Angular works. In the next article we'll deepen that knowledge and start to build up the structure of our to-do list application.

In this module