GVKun编程网logo

Angular 快速入门(一)(angular快速上手)

15

对于想了解Angular快速入门的读者,本文将提供新的信息,我们将详细介绍一,并且为您提供关于Angular4快速入门、Angular4快速入门笔记、Angular4指令快速入门、Angular4指令

对于想了解Angular 快速入门的读者,本文将提供新的信息,我们将详细介绍,并且为您提供关于Angular 4 快速入门、Angular 4 快速入门 笔记、Angular 4 指令快速入门、Angular 4 指令快速入门教程的有价值信息。

本文目录一览:

Angular 快速入门(一)(angular快速上手)

Angular 快速入门(一)(angular快速上手)

(一)下载安装node.js

下载地址

环境变量会自动配置,用path命令检查

node -v,npm -v检验是否安装成功

(二)全局安装Angular cli

管理员权限打开命令行

//可在C:/windows/system32下打开
npm install -g @angular/cli

(三)下载、安装、破解webstorm

下载地址

破解:安装完成后,License-Activaction窗口选择Licenseserver.输入网址:http://idea.iteblog.com/key.php
即可破解
也可搭建本地服务器,这样的话IntellJIdea公司的软件都可破解,而且不受网络服务器的影响。
本地服务器下载地址

(四)构建项目

  • 打开终端命令行,到要创建项目的目录下
ng new bond//需要较长时间,大部分时间在安装npm包
  • 启动服务器
ng server --open//--open会自动打开localhost:4200网页
  • 使用webstorm 创建angularjs项目


file->setting->keymap(可修改webstorm的快捷方式为eclipse的快捷方式)

  • 打开服务器


打开网页:localhost:4200
4200是默认的端口号,如果要更改,需要修改package.json文件为
ng serve –host localhost –port 4201

项目介绍

通过上述方法生成了AngularJS项目,应用代码位于src文件夹下,所有的Angular组件、模板、图片以及你的应用所需的任何东西都在那里。这个文件夹之外的文件都是为构建应用提供支持用的。

还有一些图中没有标明的文件,如下表

文件File 用途Purpose
.angular-cli.json Angular CLI的配置文件。在这个文件中,我们可以设置一系列的默认值,还可以配置项目编译时要包含的那些文件。
.editorconfig 给你的编辑器一个简单配置文件,用来确保参与你项目的每个人都具有基本的编辑器配置。
.gitignore 一个Git的配置文件,用来确保某些自动生成的文件不会被提交到源码控制系统中。
karma.conf.js 给Karma的单元测试配置,当运行ng test时会用到它。
package.json npm配置文件,其中列出了项目使用到的第三方依赖包。你还可以在这里添加自己的自定义脚本。
protractor.conf.js 给Protractor使用的端到端测试配置文件,当运行ng e2e的时候会用到。
README.md 项目的基础文档,预先写入了CLI命令的信息,别忘了用项目文档改进它,以便每个查看此仓库的人都能据此构建出你的应用。
tsconfig.json TypeScript编译器的配置,你的IDE会借助它来给你提供更好的帮助。
tslint.json 给TSLint和codelyzer用的配置信息,当运行ng lint时会用到。Lint功能可以帮你保持代码风格的统一。

Angular 4 快速入门

Angular 4 快速入门

建了个群有兴趣的朋友可以加一下 QQ 群:Angular 修仙之路 - 153742079 (群名称规则:城市 + 昵称)。

目录

  • 第一节 - 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 有什么区别

  • 不再有ControllerScope

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

  • 更好的移动端支持

  • 引入了 RxJSObservable

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

第二节 - Angular 环境搭建

基础要求

  • Node.js

  • Git

Angular 开发环境配置方式

  • 基于 Angular Quickstart

    • https://github.com/angular/qu...

  • 基于 Angular CLI

    • npm install -g @angular/cli

配置开发环境

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

基于 Angular Quickstart

  • 使用 Git 克隆 quickstart 项目

git clone https://github.com/angular/quickstart ng4-quickstart
  • 使用 IDE 打开已新建的项目 (本教程使用的 IDE 是 Visual Studio Code)

code ./ng4-quickstart
  • 安装项目所需依赖

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

npm start

基于 Angular CLI

  • 安装 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>
  `,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',<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 实际项目中,最常用的指令是 ngIfngFor 指令。

基础知识

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',<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,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],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,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,HttpModule,RouterModule],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>
      <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,RouterModule.forRoot(ROUTES)],// ...
})
export class AppModule { }

配置路由导航

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

@Component({
  selector: 'my-app',template: `
    <div>
      <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: '',providers: [MemberService],bootstrap: [AppComponent]
})
export class AppModule { }

AppComponent

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

@Component({
  selector: 'my-app',})
export class AppComponent { }

UserComponent

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


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

@Component({
    selector: 'sl-user',<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: '福建','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 4 表单快速入门

  • Angular 4 指令快速入门

  • Angular 4.x 路由快速入门

  • Angular 4 依赖注入教程之一 依赖注入简介(共八节)

  • Angular 4 组件学习线路(仅供参考)

Angular 4 快速入门 笔记

Angular 4 快速入门 笔记

https://segmentfault.com/a/1190000009733649

技术文章写的很标准,基本概念分节介绍,每节都有step,都有例子,后面例子base前面例子,最后汇总成一个大例子.

下面是划重点.

第三节 - 插值表达式 //类中定义的变量,通过{{}}在html中直接使用
在 Angular 中,我们可以使用 {{}} 插值语法实现数据绑定。

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

@Component({//it is Component
  selector: 'my-app',//selector is template container
  template: `
    ...
    <p>{{address | json}}</p>
  `,})
export class AppComponent {
  name = 'Semlinker';
  address = {
    province: '福建',city: '厦门'
  }
}
第四节 - 自定义组件
自定义组件示例
创建 UserComponent 组件
export class UserComponent {
    name = 'Semlinker';
    address = {
        province: '福建',city: '厦门'
    };
}
声明 UserComponent 组件
declarations: [ AppComponent,UserComponent]@NgModule({
  declarations: [ AppComponent,UserComponent] 
})使用 UserComponent 组件 //<sl-user> 是自定义控件UserComponent的selector.
等于在另一个文件使用UserComponent
template: `
    <sl-user></sl-user>
  `
使用构造函数初始化数据  //组件当成类,对类进行操作
constructor() {
        this.name = 'Semlinker';
        this.address = {
            province: '福建',city: '厦门'
        }
    }
第六节 - 事件绑定
在 Angular 中,我们可以通过 (eventName) 的语法,实现事件绑定。
<date-picker (dateChanged)="statement()"></date-picker>
等价于
<date-picker on-dateChanged="statement()"></date-picker>
第九节 - 注入服务
和第四节的,自定义组件,比较类似,一个类使用另一个类. 网页通常一个类对应一个网页.
创建 MemberService 服务
@Injectable()//it is 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()) //将结果转成任何类型,本例转成json类型
    }
}
配置 MemberService 服务
@NgModule({
  providers:[MemberService] //同比自定义Component。Component is  declarations: [ AppComponent,UserComponent]
})
使用 MemberService 服务
        this.memberService.getMembers()//调用http.get
            .subscribe(data => {//订阅http.get
                if (data) this.members = data;
            });
第十节 - 路由模块简介
配置路由信息
export const ROUTES: Routes = [
  { path: 'user',component: UserComponent }
];
@NgModule({
  imports: [browserModule,FormsModule,HttpModule,RouterModule.forRoot(ROUTES)],// ...
})
配置路由导航
@Component({
  selector: 'my-app',template: `
    <div>
      <nav>
        <a routerLink="/user">我的</a>
        <a routerLink="/members">Angular成员</a>
      </nav>
    </div>
  `,})
类似公司项目
dashboard.html: //导航页
<div <arouterLink="/security/global-security">{{ "GLOBAL_Security_NAV" | translation }}</a></div>
app-routing.modules.ts //内部路由
export const appRoutes: Routes = [
 {
        path: 'security',children: [
            {path: 'global-security',component: GlobalSecurityPage,canActivate: [ConferencingGuard]},]
  }
]
global-security.ts //ts实现网页 @Component({ template: ` ... ` }) export class GlobalSecurityPage implements OnInit,OnDestroy { ... }

Angular 4 指令快速入门

Angular 4 指令快速入门

建了个群有兴趣的朋友可以加一下 QQ 群:Angular 修仙之路(1)群 - 153742079 (已满),请加 Angular 修仙之路(2)群 - 648681235。

目录

  • 第一节 - 创建指令
  • 第二节 - 定义输入属性
  • 第三节 - 事件处理
  • 第四节 - 获取宿主元素属性值
  • 第五节 - 使用 <ng-template> 元素
  • 第六节 - 使用 ngTemplateOutlet 指令
  • 第七节 - 创建结构指令

阅读须知

本系列教程的开发环境及开发语言:

  • Angular 4 +
  • Angular CLI
  • TypeScript

基础知识

Angular CLI 基本使用

  • 安装 Angular CLI (可选)
npm install -g @angular/cli
  • 创建新的项目
ng new PROJECT-NAME
  • 启动本地服务器
cd PROJECT-NAME
ng serve

Angular 指令简介

Angular 的指令分为三种:

  • 组件(Component directive):用于构建UI组件,继承于 Directive 类
  • 属性指令(Attribute directive):用于改变组件的外观或行为
  • 结构指令(Structural directive):用于动态添加或删除 DOM 元素来改变 DOM 布局

Angular 指令分类图

angular-directive

Angular 组件组成图

angular-component-compose

第一节 - 创建指令

在 Angular 中,我们可以使用 HostBinding 装饰器,实现元素的属性绑定。

指令的作用

该指令用于演示如何利用 HostBinding 装饰器,设置元素的 innerText 属性。

指令的实现

import { Directive, HostBinding} from ''@angular/core'';

@Directive({
    selector: ''[greet]''
})
export class GreetDirective {
  @HostBinding() innerText = ''Hello, Everyone!'';
}

指令的应用

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

@Component({
  selector: ''app-root'',
  template: `
    <h2>Hello, Angular</h2>
    <h2 greet>Hello, Angular</h2>
  `,
})
export class AppComponent { }

第二节 - 定义输入属性

为了能够让用户自定义 GreetDirective 指令的问候内容,我们需要使用 Input 装饰器去定义指令的输入属性。

指令的作用

该指令用于演示如何利用 Input 装饰器,定义指令的输入属性,从而实现让用户自定义问候内容。

指令的实现

import { Directive, HostBinding, Input } from ''@angular/core'';

@Directive({
    selector: ''[greet]''
})
export class GreetDirective {
    @Input() greet: string;
    @HostBinding() get innerText() {
        return this.greet;
    }
}

指令的应用

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

@Component({
  selector: ''app-root'',
  template: `
    <h2>Hello, Angular</h2>
    <h2 [greet]="''Hello, Semlinker!''">Hello, Angular</h2>
  `,
})
export class AppComponent { }

第三节 - 事件处理

在 Angular 中,我们可以使用 HostListener 属性装饰器,实现元素的事件绑定。

指令的作用

该指令用于演示如何利用 HostListener 装饰器,监听用户的点击事件。

指令的实现

import { Directive, HostBinding, HostListener, Input } from ''@angular/core'';

@Directive({
    selector: ''[greet]''
})
export class GreetDirective {
   @Input() greet: string;

   @HostBinding() get innerText() {
      return this.greet;
   }

   @HostListener(''click'',[''$event'']) 
    onClick(event) {
      this.greet = ''Clicked!'';
   }
}

指令的应用

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

@Component({
  selector: ''app-root'',
  template: `
    <h2>Hello, Angular</h2>
    <h2 [greet]="''Hello, Semlinker!''">Hello, Angular</h2>
  `,
})
export class AppComponent { }

第四节 - 获取宿主元素属性值

在 Angular 中,我们可以通过 Attribute 装饰器来获取指令宿主元素的属性值。

指令的作用

该指令用于演示如何利用 Attribute 装饰器,获取指令宿主元素上的自定义属性 author 的值。

指令的实现

import { Directive, HostBinding, HostListener, Input, Attribute } from ''@angular/core'';

@Directive({
    selector: ''[greet]''
})
export class GreetDirective {
    @Input() greet: string;

    @HostBinding() get innerText() {
        return this.greet;
    }

    @HostListener(''click'',[''$event'']) 
    onClick(event) {
        this.greet = ''Clicked!'';
        console.dir(event);
    }

    constructor(@Attribute(''author'') public author: string) {
        console.log(author);
    }
}

指令的应用

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

@Component({
  selector: ''app-root'',
  template: `
    <h2>Hello, Angular</h2>
    <h2 [greet]="''Hello, Semlinker!''" 
      author="semlinker">Hello, Angular</h2>
  `,
})
export class AppComponent { }

第五节 - 使用 <ng-template> 元素

在 Angular 中,我们可以通过 ViewChild 装饰器来获取视图中定义的模板元素,然后利用 ViewContainerRef 对象的 createEmbeddedView() 方法,创建内嵌视图。

import { Component, TemplateRef, ViewContainerRef, ViewChild, 
  AfterViewInit } from ''@angular/core'';

@Component({
  selector: ''app-root'',
  template: `
    <ng-template #tpl>
      Hello, Semlinker!
    </ng-template>
  `,
})
export class AppComponent implements AfterViewInit{
  @ViewChild(''tpl'')
  tplRef: TemplateRef<any>;

  constructor(private vcRef: ViewContainerRef) {}

  ngAfterViewInit() {
    this.vcRef.createEmbeddedView(this.tplRef);
  }
}

第六节 - 使用 ngTemplateOutlet 指令

ngTemplateOutlet 的作用

该指令用于基于已有的 TemplateRef 对象,插入对应的内嵌视图。在应用 NgTemplateOutlet 指令时,我们可以通过 [ngTemplateOutletContext] 属性来设置 EmbeddedViewRef 的上下文对象。绑定的上下文应该是一个对象,此外可通过 let语法来声明绑定上下文对象属性名。

ngTemplateOutlet 的使用

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

@Component({
  selector: ''app-root'',
  template: `
    <ng-template #stpl>
      Hello, Semlinker!
    </ng-template>
    <ng-template #atpl>
      Hello, Angular!
    </ng-template>
    <div [ngTemplateOutlet]="atpl"></div>
    <div [ngTemplateOutlet]="stpl"></div>
  `,
})
export class AppComponent { }

ngOutletContext 的使用

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

@Component({
  selector: ''app-root'',
  template: `
    <ng-template #stpl let-message="message">
      <p>{{message}}</p>
    </ng-template>
    <ng-template #atpl let-msg="message">
      <p>{{msg}}</p>
    </ng-template>
    <ng-template #otpl let-msg>
      <p>{{msg}}</p>
    </ng-template>
    <div [ngTemplateOutlet]="atpl"
      [ngTemplateOutletContext]="context">
    </div>
    <div [ngTemplateOutlet]="stpl"
      [ngTemplateOutletContext]="context">
    </div>
    <div [ngTemplateOutlet]="otpl"
      [ngTemplateOutletContext]="context">
    </div>
  `,
})
export class AppComponent {
  context = { message: ''Hello ngOutletContext!'', 
    $implicit: ''Hello, Semlinker!'' };
}

第七节 - 创建结构指令

指令的功能

该指令实现 ngIf 指令相反的效果,当指令的输入条件为 Falsy 值时,显示DOM元素。

指令的实现

import { Directive, Input, TemplateRef, ViewContainerRef } from ''@angular/core'';

@Directive({
    selector: ''[exeUnless]''
})
export class UnlessDirective {

    @Input(''exeUnless'')
    set condition(newCondition: boolean) {
        if (!newCondition) { 
            this.viewContainer.createEmbeddedView(this.templateRef);
        } else {
            this.viewContainer.clear();
        }
    }

    constructor(private templateRef: TemplateRef<any>,
        private viewContainer: ViewContainerRef) {
    }
}

指令的应用

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

@Component({
  selector: ''app-root'',
  template: `
   <h2 *exeUnless="condition">Hello, Semlinker!</h2> 
  `,
})
export class AppComponent {
  condition: boolean = false;
}

我有话说

Angular 中指令与组件有什么关系?

组件继承于指令,并扩展了与 UI 视图相关的属性,如 template、styles、animations、encapsulation 等。

详细内容请参考 - Angular 2 Directive Lifecycle

结构指令中的 TemplateRefViewContainerRef 有什么作用?

TemplateRef:用于表示内嵌的 template 模板元素,通过 TemplateRef 实例,我们可以方便创建内嵌视图(Embedded Views),且可以轻松地访问到通过 ElementRef 封装后的 nativeElement。需要注意的是组件视图中的 template 模板元素,经过渲染后会被替换成 comment 元素。

ViewContainerRef:用于表示一个视图容器,可添加一个或多个视图。通ViewContainerRef 实例,我们可以基于 TemplateRef 实例创建内嵌视图,并能指定内嵌视图的插入位置,也可以方便对视图容器中已有的视图进行管理。简而言之,ViewContainerRef 的主要作用是创建和管理内嵌视图或组件视图。

详细内容请参考 - Angular 2 TemplateRef & ViewContainerRef

Angular 4 指令快速入门教程

Angular 4 指令快速入门教程

本系列教程的开发环境及开发语言:

  1. Angular 4 +
  2. Angular CLI
  3. TypeScript

基础知识

Angular CLI 基本使用

安装 Angular CLI (可选)

rush:bash;"> npm install -g @angular/cli

创建新的项目

rush:bash;"> ng new PROJECT-NAME

启动本地服务器

rush:bash;"> cd PROJECT-NAME ng serve

Angular 指令简介

Angular 的指令分为三种:

  1. 组件(Component directive):用于构建UI组件,继承于 Directive 类
  2. 属性指令(Attribute directive):用于改变组件的外观或行为
  3. 结构指令(Structural directive):用于动态添加或删除 DOM 元素来改变 DOM 布局

Angular 指令分类图

Angular 组件组成图

第一节 - 创建指令

在 Angular 中,我们可以使用 HostBinding 装饰器,实现元素的属性绑定。

指令的作用

该指令用于演示如何利用 HostBinding 装饰器,设置元素的 innerText 属性。

指令的实现

rush:js;"> import { Directive,HostBinding} from '@angular/core';

@Directive({
selector: '[greet]'
})
export class GreetDirective {
@HostBinding() innerText = 'Hello,Everyone!';
}
指令的应用
import { Component } from '@angular/core';

@Component({
selector: 'app-root',template: `

Hello,Angular

Hello,Angular

`,}) export class AppComponent { }

第二节 - 定义输入属性

为了能够让用户自定义 GreetDirective 指令的问候内容,我们需要使用 Input 装饰器去定义指令的输入属性。

指令的作用

该指令用于演示如何利用 Input 装饰器,定义指令的输入属性,从而实现让用户自定义问候内容。

指令的实现

rush:js;"> import { Directive,HostBinding,Input } from '@angular/core';

@Directive({
selector: '[greet]'
})
export class GreetDirective {
@input() greet: string;
@HostBinding() get innerText() {
return this.greet;
}
}

指令的应用

rush:js;"> import { Component } from '@angular/core';

@Component({
selector: 'app-root',Angular
<h2 [greet]="'Hello,Semlinker!'">Hello,})
export class AppComponent { }

第三节 - 事件处理

在 Angular 中,我们可以使用 HostListener 属性装饰器,实现元素的事件绑定。

指令的作用

该指令用于演示如何利用 HostListener 装饰器,监听用户的点击事件。

指令的实现

rush:js;"> import { Directive,HostListener,Input } from '@angular/core';

@Directive({
selector: '[greet]'
})
export class GreetDirective {
@input() greet: string;

@HostBinding() get innerText() {
return this.greet;
}

@HostListener('click',['$event'])
onClick(event) {
this.greet = 'Clicked!';
}
}

指令的应用

rush:js;"> import { Component } from '@angular/core';

@Component({
selector: 'app-root',})
export class AppComponent { }

第四节 - 获取宿主元素属性值

在 Angular 中,我们可以通过 Attribute 装饰器来获取指令宿主元素的属性值。

指令的作用

该指令用于演示如何利用 Attribute 装饰器,获取指令宿主元素上的自定义属性 author 的值。

指令的实现

rush:js;"> import { Directive,Input,Attribute } from '@angular/core';

@Directive({
selector: '[greet]'
})
export class GreetDirective {
@input() greet: string;

@HostBinding() get innerText() {
return this.greet;
}

@HostListener('click',['$event'])
onClick(event) {
this.greet = 'Clicked!';
console.dir(event);
}

constructor(@Attribute('author') public author: string) {
console.log(author);
}
}

指令的应用

rush:js;"> import { Component } from '@angular/core';

@Component({
selector: 'app-root',Semlinker!'"
author="semlinker">Hello,})
export class AppComponent { }

第五节 - 使用 元素

在 Angular 中,我们可以通过 ViewChild 装饰器来获取视图中定义的模板元素,然后利用 ViewContainerRef 对象的 createEmbeddedView() 方法,创建内嵌视图。

rush:js;"> import { Component,TemplateRef,ViewContainerRef,ViewChild,AfterViewInit } from '@angular/core';

@Component({
selector: 'app-root',template: `
<ng-template #tpl>
Hello,Semlinker!

`,}) export class AppComponent implements AfterViewInit{ @ViewChild('tpl') tplRef: TemplateRef;

constructor(private vcRef: ViewContainerRef) {}

ngAfterViewInit() {
this.vcRef.createEmbeddedView(this.tplRef);
}
}

第六节 - 使用 ngTemplateOutlet 指令

ngTemplateOutlet 的作用

该指令用于基于已有的 TemplateRef 对象,插入对应的内嵌视图。在应用 NgTemplateOutlet 指令时,我们可以通过 [ngTemplateOutletContext] 属性来设置 EmbeddedViewRef 的上下文对象。绑定的上下文应该是一个对象,此外可通过 let语法来声明绑定上下文对象属性名。

ngTemplateOutlet 的使用

rush:js;"> import { Component } from '@angular/core';

@Component({
selector: 'app-root',template: `
<ng-template #stpl>
Hello,Semlinker!

Hello,Angular!
`,}) export class AppComponent { }

ngOutletContext 的使用

rush:js;"> import { Component } from '@angular/core';

@Component({
selector: 'app-root',template: `
<ng-template #stpl let-message="message">

{{message}}

{{msg}}

{{msg}}

`,}) export class AppComponent { context = { message: 'Hello ngOutletContext!',$implicit: 'Hello,Semlinker!' }; }

第七节 - 创建结构指令

指令的功能

该指令实现 ngIf 指令相反的效果,当指令的输入条件为 Falsy 值时,显示DOM元素。

指令的实现

rush:js;"> import { Directive,ViewContainerRef } from '@angular/core';

@Directive({
selector: '[exeUnless]'
})
export class UnlessDirective {

@Input('exeUnless')
set condition(newCondition: boolean) {
if (!newCondition) {
this.viewContainer.createEmbeddedView(this.templateRef);
} else {
this.viewContainer.clear();
}
}

constructor(private templateRef: TemplateRef,private viewContainer: ViewContainerRef) {
}
}

指令的应用

rush:js;"> import { Component } from '@angular/core';

@Component({
selector: 'app-root',template: <h2 *exeUnless="condition"&gt;Hello,Semlinker!</h2> ,})
export class AppComponent {
condition: boolean = false;
}

我有话说

Angular 中指令与组件有什么关系?

组件继承于指令,并扩展了与 UI 视图相关的属性,如 template、styles、animations、encapsulation 等。

结构指令中的 TemplateRef 与 ViewContainerRef 有什么作用?

TemplateRef:用于表示内嵌的 template 模板元素,通过 TemplateRef 实例,我们可以方便创建内嵌视图(Embedded Views),且可以轻松地访问到通过 ElementRef 封装后的 nativeElement。需要注意的是组件视图中的 template 模板元素,经过渲染后会被替换成 comment 元素。

ViewContainerRef:用于表示一个视图容器,可添加一个或多个视图。通ViewContainerRef 实例,我们可以基于 TemplateRef 实例创建内嵌视图,并能指定内嵌视图的插入位置,也可以方便对视图容器中已有的视图进行管理。简而言之,ViewContainerRef 的主要作用是创建和管理内嵌视图或组件视图。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持小编。

总结

以上是小编为你收集整理的Angular 4 指令快速入门教程全部内容。

如果觉得小编网站内容还不错,欢迎将小编网站推荐给好友。

angularangularangularjs指令指令

JavaScript相关文章

2022最全最新前端面试题(附加解答)
这是我整理所有看过的文章的面试题+各种百度每一道题的答案,希望可以有效的帮助别人本章博客,梳理所有基础的js,jquery,vue,css, html等题,包含面试题,可供参考学习,也督促自我学习
前端面试八股文(详细版)—上
前端面试八股文,知识点广而全,内容会及时更新
Js运算符
JavaScript 语言的算术运算符是使用数字值作为操作数,进行运算之后返回一个数字值。算术运算符+,-,*,/,%% => 模(余数)
【Vue】webpack的基本使用
好处:前端开发自成体系,有一套标准的开发方案和流量。概念: webpack是前端项目工程化的具体解决方案。主要功能:它提供了友好的前端模块化开发支持,以及代码压缩混淆,处理浏览器端JavaScript的兼容性性能优化等强大的功能。好处:让程序员把工作的重心放到具体功能的实现上,提高了前端开发效率和项目的可维护性。注意:目前Vue,React等前端项目,基本上都是基于webpack进行工程化开发的。步骤import和require导入模块的区别1、require对应导出的方法是module.export
Pro3:js实现放大镜效果
JavaScript练习项目第三个:js实现放大镜的效果。
【2022-11-26】JS逆向之北京百姓网
北京百姓网cookie逆向
你评论,我赠书~【TFS-CLUB社区 第9期赠书活动】〖HTML5+CSS3+JavaScript从入门到精通(微课精编版)(第2版)〗等你来拿
你评论,我赠书~【TFS-CLUB社区 第9期赠书活动】〖HTML5+CSS3+JavaScript从入门到精通(微课精编版)〗等你来拿
App逆向案例 X嘟牛 - Frida监听 & WT-JS工具还原(一)
App逆向 X嘟牛 - Frida监听 & WT-JS工具还原(一)

今天关于Angular 快速入门的分享就到这里,希望大家有所收获,若想了解更多关于Angular 4 快速入门、Angular 4 快速入门 笔记、Angular 4 指令快速入门、Angular 4 指令快速入门教程等相关知识,可以在本站进行查询。

本文标签: