Angular 入门到精通 #01 - Introduction

421 阅读6分钟

Introduction

Angular is an application-design framework and development platform for creating efficient and sophisticated single-page apps.

这是官方给出的关于Angular的介绍,真的很简单。Angular就是一个用于开发高效的单页程序的架构和平台。

Angular is a development platform, built on TypeScript. As a platform, Angular includes:

  • A component-based framework for building scalable web applications
  • A collection of well-integrated libraries that cover a wide variety of features, including routing, forms management, client-server communication, and more
  • A suite of developer tools to help you develop, build, test, and update your code

Angular是一个基于TypeScript的开发平台,它包含了如下的部件:

  • 组件:用于基于架构去搭建可伸缩的网页应用程序
  • 可集成库的集合:包括routing, forms management, client-server communication, and more
  • 开发工具套件:帮助我们更好的搭建应用程序

The essentials

The essentials of an Angular application includes:

  • Components
  • Templates
  • Dependency injection

Angular应用程序的要素包括:

  • 组件
  • 模板
  • 依赖注入

Components

Components are the building blocks that compose an application. A component includes a TypeScript class with a @Component() decorator, an HTML template, and styles. The @Component() decorator specifies the following Angular-specific information:

  • A CSS selector that defines how the component is used in a template. HTML elements in your template that match this selector become instances of the component.
  • An HTML template that instructs Angular how to render the component
  • An optional set of CSS styles that define the appearance of the template's HTML elements

组件像砖块一样用来搭建应用程序。一个组件包括一个TypeScript类,一个HTML模板和一个样式文件。一个组件指定了如下的内容:

  • CSS选择器:定义组件如何在模板里使用。模板里的HTML元素会去匹配这个选择器。
  • HTML模板:使用组件搭建应用程序。
  • CSS样式:定义HTML元素的外观。

The following is a minimal Angular component.

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

@Component({
  selector: 'hello-world',
  template: `
    <h2>Hello World</h2>
    <p>This is my first component!</p>
  `
})
export class HelloWorldComponent {
  // The code in this class drives the component's behavior.
}

To use this component, you write the following in a template:

<hello-world></hello-world>

When Angular renders this component, the resulting DOM looks like this:

<hello-world>
    <h2>Hello World</h2>
    <p>This is my first component!</p>
</hello-world>

Templates

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

每一个组件都有一个HTML模板用于声明该组件如何被渲染,模板可以被定义在单行了,也可以定义在单独的文件。

Angular adds syntax elements that extend HTML so you can insert dynamic values from your component. Angular automatically updates the rendered DOM when your component's state changes. One application of this feature is inserting dynamic text, as shown in the following example.

Angular会添加句法元素去扩展HTML,这样我们可以在模板中插入动态的值。当组件的状态发生了变化,Angular会自动刷新DOM。下面的示例中,应用程序展示了一段动态获取的文本。

<p>{{ message }}</p>

The value for message comes from the component class:

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

@Component ({
  selector: 'hello-world-interpolation',
  templateUrl: './hello-world-interpolation.component.html'
})
export class HelloWorldInterpolationComponent {
    message = 'Hello, World!';
}

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

<p>Hello, World!</p>

Property Binding

Angular also supports property bindings, to help you set values for properties and attributes of HTML elements and pass values to your application's presentation logic.

Angular 也支持属性绑定,用于帮助我们设置HTML元素的属性值,或者在应用程序中传递值。Angular使用方括号([])表示属性绑定,可以直接赋值给绑定的属性,或者绑定一个来自组件类文件中的变量值。

<p
  [id]="sayHelloId"
  [style.color]="fontColor">
  You can set my color in the component!
</p>

Event Binding

Declare event listeners to listen for and respond to user actions such as keystrokes, mouse movements, clicks, and touches. You declare an event listener by specifying the event name in parentheses:

定义事件监听器来监听并响应用户的操作,比如keystrokes, mouse movements, clicks, and touches。事件监听器被定义在圆括号(())中。

<button
  type="button"
  [disabled]="canClick"
  (click)="sayMessage()">
  Trigger alert message
</button>

The preceding example calls a method, which is defined in the component class:

sayMessage() {
  alert(this.message);
}

The following is a combined example of Interpolation, Property Binding, and Event Binding within an Angular template:

下面是一个完整的示例,其模板中包含了Interpolation, Property Binding, and Event Binding。

hello-world-bindings.component.ts

import { Component } from '@angular/core';
 
@Component ({
  selector: 'hello-world-bindings',
  templateUrl: './hello-world-bindings.component.html'
})
export class HelloWorldBindingsComponent {
  fontColor = 'blue';
  sayHelloId = 1;
  canClick = false;
  message = 'Hello, World';
 
  sayMessage() {
    alert(this.message);
  }
}

hello-world-bindings.component.html

<button
  type="button"
  [disabled]="canClick"
  (click)="sayMessage()">
  Trigger alert message
</button>

<p
  [id]="sayHelloId"
  [style.color]="fontColor">
  You can set my color in the component!
</p>

<p>My color is {{ fontColor }}</p>

Directives

Add features to your templates by using directives. The most popular directives in Angular are *ngIf and *ngFor. Use directives to perform a variety of tasks, such as dynamically modifying the DOM structure. And create your own custom directives to create great user experiences.

可以使用指令来向模板中添加特性。Angular中最常用的指令有 *ngIf 和 *ngFor。使用指令可以完成,一系列的任务,比如动态的修改DOM。创建自定义的指令可以实现更好的用户体验。

The following code is an example of the *ngIf directive. 下面是一个 *ngIf 指令的示例。

hello-world-ngif.component.ts

import { Component } from '@angular/core';
 
@Component({
  selector: 'hello-world-ngif',
  templateUrl: './hello-world-ngif.component.html'
})
export class HelloWorldNgIfComponent {
  message = "I'm read only!";
  canEdit = false;
 
  onEditClick() {
    this.canEdit = !this.canEdit;
    if (this.canEdit) {
      this.message = 'You can edit me!';
    } else {
      this.message = "I'm read only!";
    }
  }
}

hello-world-ngif.component.html

<h2>Hello World: ngIf!</h2>

<button type="button" (click)="onEditClick()">Make text editable!</button>

<div *ngIf="canEdit; else noEdit">
    <p>You can edit the following paragraph.</p>
</div>

<ng-template #noEdit>
    <p>The following paragraph is read only. Try clicking the button!</p>
</ng-template>

<p [contentEditable]="canEdit">{{ message }}</p>

Angular's declarative templates let you cleanly separate your application's logic from its presentation. Templates are based on standard HTML, for ease in building, maintaining, and updating.

Angular的指令模板可以让我们清晰的分离应用程序的逻辑和展现。模板是基于标准的HTML,便于编译,维护和更新。

For more information on templates, see the Templates section.

Dependency injection

Dependency injection lets you declare the dependencies of your TypeScript classes without taking care of their instantiation. Instead, Angular handles the instantiation for you. This design pattern lets you write more testable and flexible code. Understanding dependency injection is not critical to start using Angular, but it is strongly recommended as a best practice. Many aspects of Angular take advantage of it to some degree.

依赖注入使得我们可以申明依赖项,而不去关心它的实例化。取而代之,Angular会负责依赖的实例化。这样的设计模式使得我们可以编写可测试的,灵活的代码。Angular不是必须使用依赖注入,但是我们强烈推荐使用。Angular在很多方面都使用了依赖注入。

To illustrate how dependency injection works, consider the following example. The first file, logger.service.ts, defines a Logger class. This class contains a writeCount function that logs a number to the console.

要想说明依赖注入是如何工作的,请参考下面的示例。logger.service.ts类定义了一个Logger类。这个类包含一个方法writeCount在console打印一个数字。

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

@Injectable({providedIn: 'root'})
export class Logger {
  writeCount(count: number) {
    console.warn(count);
  }
}

Next, the hello-world-di.component.ts file defines an Angular component. This component contains a button that uses the writeCount function of the Logger class. To access that function, the Logger service is injected into the HelloWorldDI class by adding private logger: Logger to the constructor.

文件hello-world-di.component.ts定义了一个组件。这个组件里包含一个按钮,该按钮调用了Logger类的writeCount方法。为了访问这个方法,Logger Service被注入到HelloWorldDependencyInjection类,注入的方法是添加定义 private logger: Logger 到它的构造函数里。

import { Component } from '@angular/core';
import { Logger } from '../logger.service';

@Component({
  selector: 'hello-world-di',
  templateUrl: './hello-world-di.component.html'
})
export class HelloWorldDependencyInjectionComponent  {
  count = 0;

  constructor(private logger: Logger) { }

  onLogMe() {
    this.logger.writeCount(this.count);
    this.count++;
  }
}

Angular CLI

The Angular CLI is the fastest, straightforward, and recommended way to develop Angular applications. The Angular CLI makes some tasks trouble-free. For example:

Angular CLI 是推荐的方法来构建快速的,简单的应用程序,并提供了如下的任务。

COMMANDDETAILS
ng buildCompiles an Angular application into an output directory.
ng serveBuilds and serves your application, rebuilding on file changes.
ng generateGenerates or modifies files based on a schematic.
ng testRuns unit tests on a given project.
ng e2eBuilds and serves an Angular application, then runs end-to-end tests.

For more information about the Angular CLI, see the Angular CLI Reference section.