Angular基础笔记

我会将Angular的基础事项作为备忘录记录下来。

环境

Angular版本:9.1.2
Angular CLI版本:9.1.12
Node版本:12.18.3
操作系统:win32 x64

请参照下述内容并用中文进行同义改写,只需提供一种选项:

参考资料

公式:Angular入门教程
https://angular.jp/start

用Angular入门,只需一个月的时间即可从零开始开发一个服务。

Angular教程-21-使用HTTP获取数据(httpClient.get的用法)

模板语法

HTML 上可以编写基本的模板语法
– *ngFor
– *ngIf
– 插值 {{ }} 类似于 EL 表达式。
– 属性绑定 [ ]
– 事件绑定 ( )

插值

補間構文 { } 可以在TypeScript中声明的变量的值在HTML中显示为文本。

<h1>{{ title }}</h1> // test-angularが表示される。
export class AppComponent { 
  title = 'test-angular'; 
}

属性绑定

TypeScript → HTML的绑定方向
官方说明:属性绑定单向地将值从组件属性传递到目标元素的属性。
我的理解:在用 TypeScript 定义的元素中,向使用 [ ] 包裹的DOM元素输入值。

[属性名] = “变量名”

<a [href]="url">Googleへ</a>
export class AppComponent {
  url = 'https://www.google.com';
}

上述内容将app.component的url属性绑定到HTML的a元素的href属性上。

ngFor is a directive in Angular that allows for iterating over a collection and rendering a template for each item.

在ts文件中定义数组。

import { Component } from '@angular/core'; 
@Component({ 
  selector: 'app-root', 
  templateUrl: './app.component.html', 
  styleUrls: ['./app.component.css'] 
}) 
export class AppComponent { 
  title = 'test-angular'; 
  url = 'https://www.google.com'; 
  i: number[] = [0,1,2]; 
}

使用ngFor在html文件中。

<h1>{{ title }}</h1> 
<a [href]="url">Googleへ</a> 
<div *ngFor="let item of i"> 
  <p>{{item}}</p> 
</div> 

*ngFor=”let aaa of bbb”是将bbb数组中的每个元素一个个地赋值给aaa进行提取。
类似于Java中的增强for循环。

在这个ngFor循环中,我们可以得到索引值赋给变量j,以及一个用于判断是否为第一个元素的布尔值变量f。

如果

1、在ts文件中定义一个数组。

import { Component } from '@angular/core'; 
@Component({ 
  selector: 'app-root', 
  templateUrl: './app.component.html', 
  styleUrls: ['./app.component.css'] 
}) 
export class AppComponent { 
  i: number[] = [0,1,2,null]; //追加
}

2、在HTML文件中使用ngIf

//i[3]がnullならこのdivを表示。nullでないならi3を表示。
<div *ngIf="i[3] === null; else i3"> 
  i[3]はありません。 
</div> 

// nullでない時はこちらが表示される。ng-template要素。
<ng-template #i3> 
  {{i[3]}} 
</ng-template> 

事件绑定

将HTML与TypeScript绑定。

1、将按钮的点击事件绑定到alertOn()方法上。
事件绑定可以使用(click)这样的形式,使用括号( )来包围事件。

<button (click)="alertOn()">アラート</button>

在ts文件中添加alertOn()方法。

import { Component } from '@angular/core'; 
@Component({ 
  selector: 'app-root', 
  templateUrl: './app.component.html', 
  styleUrls: ['./app.component.css'] 
}) 
export class AppComponent { 
 // alertOn()メソッドの追加。
  alertOn(): void { 
    alert('イベントバインディング'); 
  } 
}

〇主要事件列表
点击 单击
双击 双击
按下鼠标 鼠标按下
释放鼠标 鼠标释放
鼠标进入 鼠标指针进入元素
鼠标移动 鼠标指针在元素内移动
鼠标离开 鼠标指针离开元素
获得焦点 元素获得焦点
失去焦点 元素失去焦点
按下键盘 按下键盘按键
持续按压 持续按压键盘按键
释放键盘 释放键盘按键
输入 输入内容发生变化
选择 文本被选中
重置 重置时
提交 提交时

双向绑定

通过浏览器和内部脚本之间的双向输入,更新值的机制。浏览器⇔变量⇔TypeScript。

1、使用HTML创建[(ngModel)]元素。

<input type="text" name="name" [(ngModel)]="message"> 
<div> 
  メッセージ:{{ message }} 
</div>

2、使用TypeScript定义message变量。

import { Component } from '@angular/core'; 
@Component({ 
  selector: 'app-root', 
  templateUrl: './app.component.html', 
  styleUrls: ['./app.component.css'] 
}) 
export class AppComponent { 
  message: string;  //ここを追加。
}

成分

可以重复使用一系列的UI功能。
就像在Android开发中的布局一样。(在线性布局中可能会包含表格布局或图像视图等)

以下是Angular公式的引用。

组件由三个元素构成。

TypeScript:组件类处理数据和功能。在前面的部分中,组件类内的产品数据和share()方法分别处理了数据和功能。

HTML:HTML模板决定了界面。在前面的部分中,我们通过更改商品列表的HTML模板来显示每个商品的名称、描述和”Share”按钮。

CSS:组件特定的样式定义了外观和感觉。商品列表没有定义样式,但是组件的CSS存在于这里。

创建组件

在Angular CLI中

ng generate component hero-detail(コンポーネント名)

使用ng generate component会生成四个文件。
包括CSS、HTML、TypeScript和测试文件。

路由

路由(Routing)是一种根据URL动态显示内容部分的机制。
包括页面转换等操作。

路由基础1

在路由中显示aaaComponent。
1、在app-routing.module.ts中导入aaaComponent。
然后添加路径。

import { NgModule } from '@angular/core'; 
import { Routes, RouterModule } from '@angular/router'; 

import { AaaComponent } from './test/aaa/aaa.component'; // ここを追加

const routes: Routes = [ 

// ここを追加。http://localhost:4200/aaaに接続したら、AaaComponentが動作しますよということ。
  { path: 'aaa', component: AaaComponent }
]; 
@NgModule({ 
  imports: [RouterModule.forRoot(routes)], 
  exports: [RouterModule] 
}) 
export class AppRoutingModule { }

2、要定义app.module.ts引用app-routing.module.ts。

import { BrowserModule } from '@angular/platform-browser'; 
import { NgModule } from '@angular/core'; 
import { AppRoutingModule } from './app-routing.module'; 
import { AppComponent } from './app.component';  //ここを追加。 
@NgModule({ 
  declarations: [ 
    AppComponent, 
    ProductListComponent, 
    ProductDetailComponent, 
    BbbComponent 
  ], 
  imports: [ 
    BrowserModule, 
    AppRoutingModule  // ここを追加。
  ], 
  providers: [], 
  bootstrap: [AppComponent] 
}) 
export class AppModule { }

在app.component.html中添加以下内容。
这样当连接到http://localhost:4200/aaa时,将显示aaa.component.html的内容。

<router-outlet></router-outlet>

路由基础2

· 重定向
1. 在app-routing.module.ts中添加路径。
将重定向到ttp://localhost:4200/aaa。

import { NgModule } from '@angular/core'; 
import { Routes, RouterModule } from '@angular/router'; 
const routes: Routes = [ 
{ path: 'aaa', component: AaaComponent }, 
{ path: '', redirectTo: '/aaa', pathMatch: 'prefix' } //ここを追加するだけ。
]; 
@NgModule({ 
  imports: [RouterModule.forRoot(routes)], 
  exports: [RouterModule] 
}) 
export class AppRoutingModule { }

prefix: 当URL以path的值开头时(例如,在此情况下,以http://localhost:4200/开头的所有URL,除了预先定义的/aaa),将重定向到该URL。
full: 当URL与path完全匹配时(例如,在此情况下,与http://localhost:4200/完全匹配的URL),将重定向到该URL。

路由基础三

・页面跳转
在aaa.component.html和bbb.component.html之间进行跳转

在app-routing.module.ts中添加路径

import { NgModule } from '@angular/core'; 
import { Routes, RouterModule } from '@angular/router'; 
import { AaaComponent } from './test/aaa/aaa.component'; 
import { BbbComponent } from './test/bbb/bbb.component';  //追加
const routes: Routes = [ 
  { path: 'aaa', component: AaaComponent }, 
  { path: 'bbb', component: BbbComponent },  // 追加
  { path: '', redirectTo: '/aaa', pathMatch: 'prefix' }, 
]; 
@NgModule({ 
  imports: [RouterModule.forRoot(routes)], 
  exports: [RouterModule] 
}) 
export class AppRoutingModule { }

将其导入到 app.module.ts 文件中。

import { BrowserModule } from '@angular/platform-browser'; 
import { NgModule } from '@angular/core'; 
import { AppRoutingModule } from './app-routing.module'; 
import { AppComponent } from './app.component'; 
import { AaaComponent } from './test/aaa/aaa.component'; 
import { BbbComponent } from './test/bbb/bbb.component';  //追加。多分自動で追加される。
@NgModule({ 
  declarations: [ 
    AppComponent, 
    AaaComponent, 
    BbbComponent //追加。多分自動で追加される。
  ], 
  imports: [ 
    BrowserModule, 
    AppRoutingModule 
  ], 
  providers: [], 
  bootstrap: [AppComponent] 
}) 
export class AppModule { }

3、在aaa.component.html文件中添加链接。

<p>aaa works!</p> 
//http://localhost:4200/bbbに遷移。
<button [routerLink]="['/bbb']"> 
  bbbへ 
</button>

4、在bbb.component.html中添加链接。

<p>bbb works!</p> 
//http://localhost:4200/aaaに遷移。
<button [routerLink]="['/aaa']"> 
  aaaへ 
</button>

服务

引自Angular公式。

服务是Angular应用程序的必要部分。 在Angular中,服务是使用Angular的依赖注入系统能够在应用程序的任何部分使用的类的实例。 服务是共享数据在应用程序的各个部分之间的存储位置。 对于在线商店,购物车服务就是保存购物车数据和方法的位置。 相反,组件类只是被调用。

为什么需要这项服务?引用自Angular官方。

在组件内部,不应直接进行数据的获取和保存。当然,也不要故意传递临时数据。
组件应专注于数据传递,其他处理应委托给服务类。

生成服务 hero(服务名)

・服务的使用方式
参考:https://angular.jp/start/start-data

import { Injectable } from '@angular/core'; 
@Injectable({ 
  providedIn: 'root' 
}) 
export class CartService { 
items = []; 
  addToCart(product) { 
    this.items.push(product); 
  }
}

想要导入的ts文件,希望使用该服务。

import { CartService } from '../cart.service';

想要使用的服务的ts文件的构造函数中注入。

export class ProductDetailsComponent implements OnInit { 
  constructor( 
    private route: ActivatedRoute, 
    private cartService: CartService //依存性の注入
  ) { } 
}

在要使用服务的ts文件中调用方法。

export class ProductDetailsComponent implements OnInit { 
    this.cartService.addToCart(product);
}

发送GET请求

1、在app.module.ts中进行导入

import { BrowserModule } from '@angular/platform-browser'; 
import { NgModule } from '@angular/core'; 
import { AppRoutingModule } from './app-routing.module'; 
import { AppComponent } from './app.component'; 
import { HttpClientModule } from '@angular/common/http'
import { HttpClientModule } from '@angular/common/http';// ここを追加。

@NgModule({
  declarations: [
    AppComponent
  ],
imports: [ 
    BrowserModule, 
    AppRoutingModule, 
    HttpClientModule // ここを追加。
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

准备一个 JSON 文件- /assets/data/employees.json

[
  {"id": 1, "name": "Andrew", "age": 30},
  {"id": 2, "name": "Brandon", "age": 25},
  {"id": 3, "name": "Christina", "age": 26},
  {"id": 4, "name": "Elena", "age": 28},
  {"id": 5, "name": "Felicia", "age": 25}
]

2、发送一个服务类GET请求。
创建一个调用http.get方法的方法。返回类型为Observable<?>。

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { IEmployee } from './employee.model';
@Injectable({
  providedIn: 'root'
})
export class EmployeeService {

  private url: string = '/assets/data/employees.json';

  constructor(private http: HttpClient) { }

  // getの後の<IEmployee[]>はキャストらしい。
  getEmployees(): Observable<IEmployee[]> {
    return this. http.get<IEmployee[]>(this.url);
  }
}

创建一个用于返回值的模型类。

export interface IEmployee {
  id: number,
  name: string,
  age: number
}

创建一个调用http.get方法的方法的方法。

import { Component, OnInit } from '@angular/core'; 
import { EmployeeService } from './employee.service'; 
@Component({ 
  selector: 'app-root', 
  templateUrl: './app.component.html', 
  styleUrls: ['./app.component.css'] 
}) 
export class AppComponent implements OnInit{ 
  public employees = []; //返り値はここに入る 

  // 依存性の注入。EmployeeServiceの注入。 
  constructor(private employeeService: EmployeeService) {} 

  ngOnInit() { 
    // getEmployeesを呼び出し。返り値をemployees配列に代入。 
    this.employeeService.getEmployees() 
      .subscribe(data => this.employees = data); 
  } 
}

5、以HTML形式显示

<h2>Employee List</h2>
    <ul *ngFor="let employee of employees">
      <li>{{employee.name}}</li>
    </ul>
bannerAds