`
tooby
  • 浏览: 110669 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

Angular 4 basic

 
阅读更多

目录

  • 第一节 - Angular 简介

  • 第二节 - Angular 环境搭建

  • 第三节 - 插值表达式

  • 第四节 - 自定义组件

  • 第五节 - 常用指令简介

  • 第六节 - 事件绑定

  • 第七节 - 表单模块简介

  • 第八节 - Http 模块简介

  • 第九节 - 注入服务

  • 第十节 - 路由模块简介

第一节 Angular 简介

Angular 是什么

Angular 是由谷歌开发与维护一个开发跨平台应用程序的框架,同时适用于手机与桌面。

Angular 有什么特点

  • 基于 Angular 我们可以构建适用于所有平台的应用。比如:Web 应用、移动 Web 应用、移动应用和桌面应用等。

  • 通过 Web Worker和服务端渲染 (SSR),达到在如今Web平台上所能达到的最高渲染速度。

  • Angular 让你能够有效掌控可伸缩性。基于 RxJS、Immutable.js 和其它推送模型,能适应海量数据需求。

Angular 提供了哪些功能

  • 动态HTML

  • 强大的表单系统 (模板驱动和模型驱动)

  • 强大的视图引擎

  • 事件处理

  • 快速的页面渲染

  • 灵活的路由

  • HTTP 服务

  • 视图封装

  • AOT、Tree Shaking

Angular 与 AngularJS 有什么区别

  • 不再有Controller和 Scope

  • 更好的组件化及代码复用

  • 降低了学习曲线

  • 更好的移动端支持

  • 引入了 RxJS 与 Observable

  • 引入了 Zone.js,提供更加智能的变化检测

第二节 - Angular 环境搭建

基础要求

npm镜像

 

原镜像

https://registry.npmjs.org/

淘宝npm镜像

cnpmjs镜像

有很多方法来配置npm的registry地址,下面根据不同情境列出几种比较常用的方法。以淘宝npm镜像举例:

1.临时使用

npm --registry https://registry.npm.taobao.org install express

2.持久使用

npm config set registry https://registry.npm.taobao.org

// 配置后可通过下面方式来验证是否成功
npm config get registry
// 或
npm info express

3.通过cnpm使用

npm install -g cnpm --registry=https://registry.npm.taobao.org

// 使用
cnpm install expresstall express

Angular 开发环境配置方式

配置开发环境

本快速入门教程,选用第一种配置方式搭建 Angular 开发环境:

基于 Angular Quickstart

  • 使用 Git 克隆 quickstart 项目

git clone https://github.com/angular/quickstart ng4-quickstart
code ./ng4-quickstart
  • 安装项目所需依赖

npm i
  • 验证环境是否搭建成功

npm start

基于 Angular CLI

npm install -g @angular/cli
  • 检测 Angular CLI 是否安装成功

ng --version
  • 创建新的项目

ng new PROJECT-NAME
  • 启动本地服务器

cd PROJECT-NAME
ng serve

第三节 - 插值表达式

在 Angular 中,我们可以使用 {{}} 插值语法实现数据绑定。

绑定普通文本

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

@Component({
  selector: 'my-app',
  template: `<h1>Hello {{name}}</h1>`,
})
export class AppComponent  {
  name = 'Angular'; 
}

绑定对象属性

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

@Component({
  selector: 'my-app',
  template: `
    <h2>大家好,我是{{name}}</h2>
    <p>我来自<strong>{{address.province}}</strong>省,
      <strong>{{address.city}}</strong>市
    </p>
  `,
})
export class AppComponent {
  name = 'Semlinker';
  address = {
    province: '福建',
    city: '厦门'
  }
}

值得一提的是,我们可以使用 Angular 内置的 json 管道,来显示对象信息:

@Component({
  selector: 'my-app',
  template: `
    ...
    <p>{{address | json}}</p>
  `,
})
export class AppComponent {
  name = 'Semlinker';
  address = {
    province: '福建',
    city: '厦门'
  }
}

第四节 - 自定义组件

在 Angular 中,我们可以通过 Component 装饰器和自定义组件类来创建自定义组件。

基础知识

定义组件的元信息

在 Angular 中,我们可以使用 Component 装饰器来定义组件的元信息:

@Component({
  selector: 'my-app', // 用于定义组件在HTML代码中匹配的标签
  template: `<h1>Hello {{name}}</h1>`, // 定义组件内嵌视图
})

定义组件类

export class AppComponent  {
  name = 'Angular'; 
}

定义数据接口

在 TypeScript 中的接口是一个非常灵活的概念,除了可用于对类的一部分行为进行抽象以外,也常用于对「对象的形状(Shape)」进行描述。

interface Person {
  name: string;
  age: number;
}

let semlinker: Person = {
  name: 'semlinker',
  age: 31
};

自定义组件示例

创建 UserComponent 组件

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

@Component({
    selector: 'sl-user',
    template: `
    <h2>大家好,我是{{name}}</h2>
    <p>我来自<strong>{{address.province}}</strong>省,
      <strong>{{address.city}}</strong>市
    </p>
    `
})
export class UserComponent {
    name = 'Semlinker';
    address = {
        province: '福建',
        city: '厦门'
    };
}

声明 UserComponent 组件

// ...
import { UserComponent } from './user.component';
@NgModule({
  imports:      [ BrowserModule ],
  declarations: [ AppComponent, UserComponent],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

使用 UserComponent 组件

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

@Component({
  selector: 'my-app',
  template: `
    <sl-user></sl-user>
  `,
})
export class AppComponent {}

使用构造函数初始化数据

@Component({...})
export class UserComponent {
    name: string;
    address: any;

    constructor() {
        this.name = 'Semlinker';
        this.address = {
            province: '福建',
            city: '厦门'
        }
    }
}

接口使用示例

定义 Address 接口

interface Address {
    province: string;
    city: string;
}

使用 Address 接口

export class UserComponent {
    name: string;
    address: Address;
    // ...
}

第五节 - 常用指令简介

在 Angular 实际项目中,最常用的指令是 ngIf 和 ngFor 指令。

基础知识

ngIf 指令简介

该指令用于根据表达式的值,动态控制模板内容的显示与隐藏。它与 AngularJS 1.x 中的 ng-if 指令的功能是等价的。

ngIf 指令语法

<div *ngIf="condition">...</div>

ngFor 指令简介

该指令用于基于可迭代对象中的每一项创建相应的模板。它与 AngularJS 1.x 中的 ng-repeat 指令的功能是等价的。

ngFor 指令语法

<li *ngFor="let item of items;">...</li>

ngIf 与 ngFor 指令使用示例

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

interface Address {
    province: string;
    city: string;
}

@Component({
    selector: 'sl-user',
    template: `
    <h2>大家好,我是{{name}}</h2>
    <p>我来自<strong>{{address.province}}</strong>省,
      <strong>{{address.city}}</strong>市
    </p>
    <div *ngIf="showSkills">
        <h3>我的技能</h3>
        <ul>
            <li *ngFor="let skill of skills">
                {{skill}}
            </li>
        </ul>
    </div>
    `
})
export class UserComponent {
    name: string;
    address: Address;
    showSkills: boolean;
    skills: string[];

    constructor() {
        this.name = 'Semlinker';
        this.address = {
            province: '福建',
            city: '厦门'
        };
        this.showSkills = true;
        this.skills = ['AngularJS 1.x', 'Angular 2.x', 'Angular 4.x'];
    }
}

第六节 - 事件绑定

在 Angular 中,我们可以通过 (eventName) 的语法,实现事件绑定。

基础知识

事件绑定语法

<date-picker (dateChanged)="statement()"></date-picker>

等价于

<date-picker on-dateChanged="statement()"></date-picker>

介绍完事件绑定的语法,接下来我们来为第五节中的 UserComponent 组件,开发一个功能,即可以让用户动态控制技能信息的显示与隐藏。

事件绑定示例

@Component({
    selector: 'sl-user',
    template: `
    ...
    <button (click)="toggleSkills()">
        {{ showSkills ? "隐藏技能" : "显示技能" }}
    </button>
    ...
    `
})
export class UserComponent {
    // ...
    toggleSkills() {
        this.showSkills = !this.showSkills;
    }
}

第七节 - 表单模块简介

Angular 中有两种表单:

  • Template Driven Forms - 模板驱动式表单 (类似于 AngularJS 1.x 中的表单 )

  • Reactive Forms - 响应式表单

本小节主要介绍模板驱动式的表单,接下来我们来演示如何通过表单来为我们的之前创建的 UserComponent 组件,增加让用户自定义技能的功能。

基础知识

导入表单模块

import { FormsModule } from '@angular/forms';
// ...
@NgModule({
  imports: [BrowserModule, FormsModule],
  declarations: [AppComponent, UserComponent],
  bootstrap: [AppComponent]
})
export class AppModule { }

模板变量语法

<video #player></video> 
<button (click)="player.pause()">Pause</button>

等价于

<video ref-player></video>

表单使用示例

@Component({
    selector: 'sl-user',
    template: `
    ...
    <div *ngIf="showSkills">
        <h3>我的技能</h3>
        ...
        <form (submit)="addSkill(skill.value)">
            <label>添加技能</label>
            <input type="text" #skill>
        </form>
    </div>
    `
})
export class UserComponent {
   // ...
    addSkill(skill: string) {
        let skillStr = skill.trim();
        if (this.skills.indexOf(skillStr) === -1) {
            this.skills.push(skillStr);
        }
    }
}

第八节 - Http 模块简介

基础知识

导入 Http 模块

// ... 
import { HttpModule } from '@angular/http';

@NgModule({
  imports: [BrowserModule, FormsModule, HttpModule],
  declarations: [AppComponent, UserComponent],
  bootstrap: [AppComponent]
})
export class AppModule { }

使用 Http 服务步骤

(1) 从 @angular/http 模块中导入 Http 类

(2) 导入 RxJS 中的 map 操作符

(3) 使用 DI 方式注入 http 服务

(4) 调用 http 服务的 get() 方法,设置请求地址并发送 HTTP 请求

(5) 调用 Response 对象的 json() 方法,把响应体转成 JSON 对象

(6) 把请求的结果,赋值给对应的属性

Http 服务使用示例

使用 Http 服务

import { Component, OnInit } from '@angular/core';
import { Http } from '@angular/http'; // (1)
import 'rxjs/add/operator/map'; // (2)

interface Member {
    id: string;
    login: string;
    avatar_url: string;
}

@Component({
    selector: 'sl-members',
    template: `
    <h3>Angular Orgs Members</h3>
    <ul *ngIf="members">
      <li *ngFor="let member of members;">
        <p>
          <img [src]="member.avatar_url" width="48" height="48"/>
          ID:<span>{{member.id}}</span>
          Name: <span>{{member.login}}</span>
        </p>
      </li>
    </ul>
    `
})
export class MembersComponent implements OnInit {
  members: Member[];

  constructor(private http: Http) { } // (3)

  ngOnInit() {
    this.http.get(`https://api.github.com/orgs/angular/members?page=1&per_page=5`) // (4)
        .map(res => res.json()) // (5)
        .subscribe(data => {
           if (data) this.members = data; // (6)
        });
    }
}

声明 MembersComponent 组件

// ...
import { MembersComponent } from './members.component';

@NgModule({
  imports: [BrowserModule, FormsModule, HttpModule],
  declarations: [AppComponent, UserComponent, MembersComponent],
  bootstrap: [AppComponent]
})
export class AppModule { }

使用 MembersComponent 组件

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

@Component({
  selector: 'my-app',
  template: `
    <sl-members></sl-members>
  `,
})
export class AppComponent {}

第九节 - 注入服务

基础知识

组件中注入服务步骤

(1) 配置已创建的服务,如:

@NgModule({
  // ...
  providers: [MemberService]
})
export class AppModule { }

(2) 导入已创建的服务,如:

import { MemberService } from '../member.service';

(3) 使用构造注入方式,注入服务:

export class MembersComponent implements OnInit {
   // ...
   constructor(private memberService: MemberService) { }
}

服务使用示例

创建 MemberService 服务

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

@Injectable()
export class MemberService {
    constructor(private http: Http) { }

    getMembers() {
        return this.http
            .get(`https://api.github.com/orgs/angular/members?page=1&per_page=5`)
            .map(res => res.json())
    }
}

配置 MemberService 服务

import { MemberService } from "./member.service";

@NgModule({
  // ...
  providers:[MemberService],
  bootstrap: [AppComponent]
})
export class AppModule { }

使用 MemberService 服务

// ...
import { MemberService } from "./member.service";

@Component({...})
export class MembersComponent implements OnInit {
    members: Member[];

    constructor(private memberService: MemberService) { }

    ngOnInit() {
        this.memberService.getMembers()
            .subscribe(data => {
                if (data) this.members = data;
            });
    }
}

第十节 - 路由模块简介

基础知识

导入路由模块

// ...
import { RouterModule } from '@angular/router';

@NgModule({
  imports: [BrowserModule, FormsModule, HttpModule, RouterModule],
  declarations: [AppComponent, UserComponent, MembersComponent],
  bootstrap: [AppComponent]
})
export class AppModule { }

配置路由信息

import { Routes, RouterModule } from '@angular/router';
import { UserComponent } from './user.component';

export const ROUTES: Routes = [
  { path: 'user', component: UserComponent }
];

@NgModule({
  imports: [
    BrowserModule,
    RouterModule.forRoot(ROUTES)
  ],
  // ...
})
export class AppModule {}

routerLink 指令

为了让我们链接到已设置的路由,我们需要使用 routerLink 指令,具体示例如下:

<nav>
  <a routerLink="/">首页</a>
  <a routerLink="/user">我的</a>
</nav>

当我们点击以上的任意链接时,页面不会被重新加载。反之,我们的路径将在 URL 地址栏中显示,随后进行后续视图更新,以匹配routerLink 中设置的值。

router-outlet 指令

该指令用于告诉 Angular 在哪里加载组件,当 Angular 路由匹配到响应路径,并成功找到需要加载的组件时,它将动态创建对应的组件,并将其作为兄弟元素,插入到 router-outlet 元素中。具体示例如下:

@Component({
  selector: 'app-root',
  template: `
    <div class="app">
      <h3>Our app</h3>
      <router-outlet></router-outlet>
    </div>
  `
})
export class AppComponent {}

路由使用示例

配置路由信息

export const ROUTES: Routes = [
  { path: '', pathMatch: 'full', redirectTo: 'user' },
  { path: 'user', component: UserComponent },
  { path: 'members', component: MembersComponent }
];

@NgModule({
  imports: [BrowserModule, FormsModule, HttpModule,
    RouterModule.forRoot(ROUTES)],
  // ...
})
export class AppModule { }

配置路由导航

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

@Component({
  selector: 'my-app',
  template: `
    <div class="app">
      <h1>欢迎来到Angular的世界</h1>
      <nav>
        <a routerLink="/user">我的</a>
        <a routerLink="/members">Angular成员</a>
      </nav>
      <router-outlet></router-outlet>
    </div>
  `,
})
export class AppComponent { }

完整示例

AppModule

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule, Routes } from '@angular/router';

import { AppComponent } from './app.component';
import { UserComponent } from './user.component';
import { MembersComponent } from './members.component';
import { MemberService } from "./member.service";

export const ROUTES: Routes = [
  { path: '', pathMatch: 'full', redirectTo: 'user' },
  { path: 'user', component: UserComponent },
  { path: 'members', component: MembersComponent }
];

@NgModule({
  imports: [BrowserModule, FormsModule, HttpModule,
    RouterModule.forRoot(ROUTES)],
  declarations: [AppComponent, UserComponent, MembersComponent],
  providers: [MemberService],
  bootstrap: [AppComponent]
})
export class AppModule { }

AppComponent

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

@Component({
  selector: 'my-app',
  template: `
    <div class="app">
      <h1>欢迎来到Angular的世界</h1>
      <nav>
        <a routerLink="/user">我的</a>
        <a routerLink="/members">Angular成员</a>
      </nav>
      <router-outlet></router-outlet>
    </div>
  `,
})
export class AppComponent { }

UserComponent

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


interface Address {
    province: string;
    city: string;
}

@Component({
    selector: 'sl-user',
    template: `
    <h2>大家好,我是{{name}}</h2>
    <p>我来自<strong>{{address.province}}</strong>省,
      <strong>{{address.city}}</strong>市
    </p>
    <button (click)="toggleSkills()">
        {{ showSkills ? "隐藏技能" : "显示技能" }}
    </button>
    <div *ngIf="showSkills">
        <h3>我的技能</h3>
        <ul>
            <li *ngFor="let skill of skills">
                {{skill}}
            </li>
        </ul>
        <form (submit)="addSkill(skill.value)">
            <label>添加技能</label>
            <input type="text" #skill>
        </form>
    </div>
    `
})
export class UserComponent {
    name: string;
    address: Address;
    showSkills: boolean;
    skills: string[];

    constructor() {
        this.name = 'Semlinker';
        this.address = {
            province: '福建',
            city: '厦门'
        };
        this.showSkills = true;
        this.skills = ['AngularJS 1.x', 'Angular 2.x', 'Angular 4.x'];
    }

    toggleSkills() {
        this.showSkills = !this.showSkills;
    }

    addSkill(skill: string) {
        let skillStr = skill.trim();
        if (this.skills.indexOf(skillStr) === -1) {
            this.skills.push(skillStr);
        }
    }
}

MembersComponent

import { Component, OnInit } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

import { MemberService } from "./member.service";

interface Member {
    id: string;
    login: string;
    avatar_url: string;
}

@Component({
    selector: 'sl-members',
    template: `
    <h3>Angular Orgs Members</h3>
    <ul *ngIf="members">
      <li *ngFor="let member of members;">
        <p>
          <img [src]="member.avatar_url" width="48" height="48"/>
          ID:<span>{{member.id}}</span>
          Name: <span>{{member.login}}</span>
        </p>
      </li>
    </ul>
    `
})
export class MembersComponent implements OnInit {
    members: Member[];

    constructor(private memberService: MemberService) { }

    ngOnInit() {
        this.memberService.getMembers()
            .subscribe(data => {
                if (data) this.members = data;
            });
    }
}

MemberService

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

@Injectable()
export class MemberService {
    constructor(private http: Http) { }

    getMembers() {
        return this.http
            .get(`https://api.github.com/orgs/angular/members?page=1&per_page=5`)
            .map(res => res.json())
    }
}

我有话说

除了本系列教程外,还有其它学习资源么?

本系列教程的主要目的是让初学者对 Angular 的相关基础知识,有一定的了解。除了本系列教程外,初学者还可以参考以下教程:

分享到:
评论

相关推荐

    angular-basicauth:AngularJs服务,用于管理登录注销和API端点的基本身份验证

    #angular-basicauth 目的 简单的AngularJs服务,用于管理登录和注销以及使用基本身份验证来保护服务器API端点。 它提供以下功能: 用于处理登录和注销操作的服务 根据默认为/ api / authentication的可配置服务器...

    java-angular-basic

    java-angular-basic

    Angular-Basic-2.0

    Angular-Basic-2.0 Angular是由Google创建和维护的功能齐全的Javascript框架,用于构建全栈应用程序的前端部分。 Angular在大型企业中非常受欢迎。 AngularJS于2010年发布。不建议使用,应将其更新为angular。 ...

    gojs-angular-basic:一个简单的项目演示了我们的GoJSAngular组件的用法

    gojs-angular-basic由Northwoods Software for该项目提供了在Angular应用程序中使用GoJS的基本示例。 请查看的了解更多信息。 它使用包来处理设置Diagram,Palette和Overview组件。 运行示例时,请尝试移动/添加/...

    Angular: Up and Running: Learning Angular, Step by Step2018

    Chapter 4, Understanding and Using Angular Components, covers Angular components in more detail, as well as the various options available when creating them. It also covers the basic lifecycle hooks ...

    basic-Angular:Proyecto Angular con manejo de componetes y redireccion de rutas

    basic-Angular:Proyecto Angular con manejo de componetes y redireccion de rutas

    slush-angular-basic:我用于开发angular webapp的个人模板

    #slush-angular-basic ##我用于开发有角度的webapp的个人模板 在查看维基 感谢@lucasmezencio对环境的任务! 由3&gt;制成:Diel Duarte

    Expert Angular

    This book is for JavaScript developers with some prior exposure to Angular, at least through basic examples. We assume that you've got working knowledge of HTML, CSS, and JavaScript. What You Will ...

    Angular Services

    This book starts with a basic rundown on how you can create your own Angular 2 development environment. You will then use Bootstrap and Angular UI components to create pages. You will also understand...

    v8_angular-basic:Angular教程简介

    Angular,应用程序开发简介 创建多平台,可扩展和干净的应用程序。 实用车间 介绍 本角度课程介绍了对专业项目的必要实践的研究。 这是一门高级课程,因此将需要最少的... 4流 5注 6-Http 7手表 8React式 9材料

    Learning Angular 2.pdf

    basic concepts and sample components and iterating on them to build up more complex functionalities in every chapter until we launch a complete, tested, production-ready sample web application by the ...

    angular-basic-app-service:您可以扩展的基本应用服务,其中包含处理常见事件的代码,例如调整大小、方向变化、滚动等

    如何安装 bower install angular-basic-app-service --save如何使用在您的应用程序中引用该模块。 ( function ( ) { angular . module ( 'someApp' , [ 'angular.basicAppService' ] ) ;} ) ( ) ; 通过扩展 ...

    Rails.Angular.Postgres.and.Bootstrap.2nd.Edition

    Chapter 4. Perform Fast Queries with Advanced Postgres Indexes Chapter 5. Create Clean Search Results with Bootstrap Components Chapter 6. Build a Dynamic UI with AngularJS Chapter 7. Test This Fancy ...

    skbank-angular-basic

    AngularBasic 该项目是使用版本6.0.0生成的。 开发服务器 为开发服务器运行ng serve 。... 如果您更改任何源文件,该应用程序将自动重新加载。...要获得有关Angular CLI的更多帮助,请使用ng help或查看 。

    Angular-basic-project

    角度的 该项目是使用版本9.1.7生成的。 开发服务器 为开发服务器运行ng serve 。... 如果您更改任何源文件,该应用程序将自动重新加载。 ...要获得有关Angular CLI的更多帮助,请使用ng help或查看 。

    angular-basic-concepts

    NGBasic概念 该项目是使用版本11.2.2生成的。 开发服务器 为开发服务器运行ng serve 。...如果您更改任何源文件,该应用程序将自动重新加载。...要获得有关Angular CLI的更多帮助,请使用ng help或查看“ 页面。

    Angular-basic:角度介绍

    基地 该项目是使用版本11.2.8生成的。 开发服务器 为开发服务器运行ng serve 。... 如果您更改任何源文件,该应用程序将自动重新加载。...要获得有关Angular CLI的更多帮助,请使用ng help或查看“ 页面。

    Building Single Page Application Using ASP.NET Core & Angular

    Building Single Page App using ASP.NET Core and Angular is not at all meant for freshers or for those who just started programming. Building Single Page App using ASP.NET Core and Angular is written ...

Global site tag (gtag.js) - Google Analytics