Web前端学习笔记——AngularJS之指令、表单处理、和服务端交互、路由处理、Angular CLI

目录

指令

NgClass

NgStyle

NgModel

NgIf

NgSwitch

NgFor

带索引的 *ngFor

自定义指令

表单处理

和服务端交互

启用 Http 服务

发起一个 get 请求

Reading the full response

错误处理

路由处理

基本用法

路由对象

动态路由匹配

路由导航

Angular CLI

安装

依赖

安装

使用帮助

初始化项目

启动开发服务

创建组件,指令,过滤器和服务

在脚手架项目中使用 SASS 预处理器

更新 Angular CLI

其它

切换包管理器

详细参考文档


指令

在 Angular 中最常用的指令分为两种,它们分别是 属性型指令 和 结构型指令

NgClass

  • 作用:添加或移除一组 CSS 类

NgStyle

  • 作用:添加或移除一组 CSS 样式

NgModel

  • 作用:双向绑定到 HTML 表单元素

NgIf

  • 作用:根据条件添加或移除 DOM
  • 语法:
<div class="box" *ngIf="false">看不见我</div>

我们也可以通过类绑定样式绑定来显示或隐藏一个元素。

<!-- isSpecial is true -->
<div [class.hidden]="!isSpecial">Show with class</div>
<div [class.hidden]="isSpecial">Hide with class</div>

<div [style.display]="isSpecial ? 'block' : 'none'">Show with style</div>
<div [style.display]="isSpecial ? 'none'  : 'block'">Hide with style</div>

NgSwitch

  • 作用:类似于 JavaScript 中的 switch 语句,根据条件渲染多个选项中的一个。
  • 语法:该指令包括三个相互协作的指令:NgSwitchNgSwitchCaseNgSwitchDefault
<div [ngSwitch]="currentHero.emotion">
  <app-happy-hero    *ngSwitchCase="'happy'"    [hero]="currentHero"></app-happy-hero>
  <app-sad-hero      *ngSwitchCase="'sad'"      [hero]="currentHero"></app-sad-hero>
  <app-confused-hero *ngSwitchCase="'confused'" [hero]="currentHero"></app-confused-hero>
  <app-unknown-hero  *ngSwitchDefault           [hero]="currentHero"></app-unknown-hero>
</div>

NgFor

  • 作用:列表渲染
  • 语法:
<div *ngFor="let hero of heroes">{{hero.name}}</div>

带索引的 *ngFor

<ul>
  <li *ngFor="let item of todos; let i = index">{{ item.title + i }}</li>
</ul>

自定义指令

参考文档:

表单处理

参考文档:https://angular.io/guide/user-input

和服务端交互

启用 Http 服务

  • open the root AppModule,
  • import the HttpClientModule symbol from @angular/common/http,
  • add it to the @NgModule.imports array.
// app.module.ts:

import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';

// Import HttpClientModule from @angular/common/http
import {HttpClientModule} from '@angular/common/http';

@NgModule({
  imports: [
    BrowserModule,
    // Include it under 'imports' in your application module
    // after BrowserModule.
    HttpClientModule,
  ],
})
export class MyAppModule {}

发起一个 get 请求

@Component(...)
export class MyComponent implements OnInit {

  results: string[];

  // Inject HttpClient into your component or service.
  constructor(private http: HttpClient) {}

  ngOnInit(): void {
    // Make the HTTP request:
    this.http.get('/api/items').subscribe(data => {
      // Read the result field from the JSON response.
      this.results = data['results'];
    });
  }
}

Reading the full response

this.http
  .get('https://jsonplaceholder.typicode.com/posts/1', {observe: 'response'})
  .subscribe(res => {
  console.log(res)
})

结果示例:

 

错误处理

http
  .get('/api/items')
  .subscribe(
    // Successful responses call the first callback.
    data => {...},
    // Errors will call this callback instead:
    err => {
      console.log('Something went wrong!');    
    }
  );

路由处理

基本用法

  1. 添加 AppRoutingModule
ng generate module app-routing --flat --module=app

app-routing.module.ts

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

import { FooComponent } from './foo/foo.component'
import { BarComponent } from './bar/bar.component'

const routes: Routes = [
  {
    path: 'foo',
    component: FooComponent
  },
  {
    path: 'bar',
    component: BarComponent
  }
]

@NgModule({
  imports: [
    RouterModule.forRoot(routes)
  ],
  exports: [ RouterModule ]
})
export class AppRoutingModule {}

设置路由出口:

<h1>{{title}}</h1>
<router-outlet></router-outlet>

设置导航链接:

<ul>
  <li>
    <a routerLink="/foo">Go Foo</a>
  </li>
  <li>
    <a routerLink="/bar">Go Foo</a>
  </li>
</ul>

路由对象

  • path
    • 不能以 / 开头
  • component

默认路由:

{ path: '', redirectTo: '/dashboard', pathMatch: 'full' },

动态路由匹配

动态路径配置:

{ path: 'detail/:id', component: HeroDetailComponent },

导航链接:

<a *ngFor="let hero of heroes" class="col-1-4"
    routerLink="/detail/{{hero.id}}">

在组件中解析获取动态路径参数:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Location } from '@angular/common';

@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {

  constructor(
    private route: ActivatedRoute,
    private location: Location
  ) { }

  ngOnInit() {
    const id = this.route.snapshot.paramMap.get('id')
    console.log(id)
  }

}

路由导航

后退:

this.location.back();

Angular CLI

Edit on github

illustration-home-inverted.91b07808be

安装

依赖

  • Node 6.9.0 or higher
  • NPM 3 or higher
  • Python
  • C++ 编译工具

安装

npm install -g @angular/cli

使用帮助

ng help

初始化项目

ng new <项目名称>

启动开发服务

ng serve

ng serve 默认占用 4200 端口号,可以通过下面选项配置:

ng serve --port 4201

创建组件,指令,过滤器和服务

# 创建组件
ng generate component my-new-component

# 创建组件别名
ng g component my-new-component # using the alias

# components support relative path generation
# if in the directory src/app/feature/ and you run
ng g component new-cmp
# your component will be generated in src/app/feature/new-cmp
# but if you were to run
ng g component ../newer-cmp
# your component will be generated in src/app/newer-cmp
# if in the directory src/app you can also run
ng g component feature/new-cmp
# and your component will be generated in src/app/feature/new-cmp

可辅助创建资源的功能列表:

ScaffoldUsage
Componentng g component my-new-component
Directiveng g directive my-new-directive
Pipeng g pipe my-new-pipe
Serviceng g service my-new-service
Classng g class my-new-class
Guardng g guard my-new-guard
Interfaceng g interface my-new-interface
Enumng g enum my-new-enum
Moduleng g module my-module

angular-cli will add reference to componentsdirectives and pipes automatically in the app.module.ts. If you need to add this references to another custom module, follow this steps:

  1. ng g module new-module to create a new module
  2. call ng g component new-module/new-component

This should add the new componentdirective or pipe reference to the new-module you've created.

在脚手架项目中使用 SASS 预处理器

SASS 是一款非常好用的 CSS 预编译器,Bootstrap 官方从4.0开始已经切换到了 SASS。

如果想要在脚手架项目中使用 SASS 预处理器,我们需要自己手动修改一些配置文件,请按照以下步骤依次修改:

  • angular-cli.json 里面的 styles.css 后缀改成 .scss

1515424529111

当你后面再使用 ng g c *** 自动创建组件的时候,默认就会生成 .scss 后缀的样式文件了。

  • angular-cli.json 里面的 styleExt 改成 .scss

1515424609137

  • src 下面 styles.css 改成 styles.scss

1515424718388

  • app.component.scss

1515424763294

  • app.component.ts 里面对应修改

1515424806351

改完之后,重新 ng serve,打开浏览器查看效果。

SASS 的 API 请参考官方网站 。

SASS 只是一个预编译器,它支持所有 CSS 原生语法。利用 SASS 可以提升你的 CSS 编码效率,增强 CSS 代码的可维护性,但是千万不要幻想从此就可以不用学习 CSS 基础知识了。

更新 Angular CLI

其它

切换包管理器

# 默认为 npm
ng set --global packageManager=npm

# 将包管理器设置为 yarn
ng set --global packageManager=yarn

# 将包管理器设置为 cnpm
ng set --global packageManager=cnpm

详细参考文档

https://github.com/angular/angular-cli/wiki

 

 

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值