Angular4


Angular4.x 安装 、创建项目、 目录结
构介绍 、 创建组件
主讲教师:( 大地 )
合作网站:www.itying.com (T IT 营)
合作网站:www.ionic.wang ( Ionic 中文网 )
目录
一、安装最新版本的nodejs ............................................................................................ 1
二、全局安装 Angular CLI 脚手架工具(只需要安装一次)。 ........................................... 1
三、创建项目.................................................................................................................. 2
四、目录结构分析 .......................................................................................................... 3
五、Hello Angular 4.0 以及 app.module.ts、组件分析 .................................................. 6
的 一、安装最新版本的 nodejs
注意 :请先在终端/控制台窗口中运行命令 node -v 和 npm -v , 来验证一下你正在运行
node 6.9.x 和 npm 3.x.x 以上的版本。 更老的版本可能会出现错误,更新的版本则没问
题。
二、 全局安装 Angular CLI 脚手架工具( 只需
要安装一次) 。
1. 使用 npm 命令安装
npm install -g @angular/cli
2. 安装 cnpm
npm 可能安装失败建议先用 npm 安装一下 cnpm 用淘宝镜像安装
https://npm.taobao.org/
npm install -g cnpm --registry=https://registry.npm.taobao.org
3. 使用 cnpm 命令安装
cnpm install -g @angular/cli
三、创建项目
1. 打开 cmd 找到你要创建项目的目录
2. 创建项目
ng new 项目名称 创建一个项目
ng new my-app
3. 进入刚才创建的项目里面启动服务
cd my-app
cnpm install //安装依赖
ng serve --open
四、目录结构分析
1. 项目创建完成后的目录结构: :
文件 用途
e2e/
在 e2e/ 下是端到端(End-to-End)测试。 它们不在 src/ 下,是
因为端到端测试实际上和应用是相互独立的,它只适用于测试你的
应用而已。 这也就是为什么它会拥有自己的 tsconfig.json 。
S S rc
node_modules/
我们在 的项目的所有文件得放在 src 里面, 所有的 Angular 组件、模
板、样式、图片以及你的应用所需的任何东西都在那里。
Node.js 创建了这个文件夹,并且把 package.json 中列举的所有
第三方模块都放在其中。
.angular-cli.json
Angular CLI 的配置文件。 在这个文件中,我们可以设置一系列默
认值,还可以配置项目编译时要包含的那些文件。 要了解更多,
请参阅它的官方文档。
.editorconfig
给你的编辑器看的一个简单配置文件,它用来确保参与你项目的每
个人都具有基本的编辑器配置。 大多数的编辑器都支
持 .editorconfig 文件,详情参见 http://editorconfig.org 。
.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 功能可以帮你保持代码风格的统一。
2.src 目录结构: :
文件 用途
app/app.component.{ts,html,css,spec.ts}
组件 使用 HTML模板、CSS 样式和单元测
试定义 AppComponent 组件。 它是 根组件,
随着应用的成长它会成为一棵组件树的根
节点。
app/app.module.ts
定义 AppModule ,这个根模块会告诉
Angular 如何组装该应用。 目前,它只声明
了 AppComponent 。 稍后它还会声明更多
组件。
assets/*
静态资源 这个文件夹下你可以放图片等
任何东西,在构建应用时,它们全都会拷贝
到发布包中。
environments/*
这个文件夹中包括为各个目标环境准备的
文件,它们导出了一些应用中要用到的配置
变量。 这些文件会在构建应用时被替换。
比如你可能在产品环境中使用不同的 API
端点地址,或使用不同的统计 Token 参数。
甚至使用一些模拟服务。 所有这些,CLI
都替你考虑到了。
favicon.ico
每个网站都希望自己在书签栏中能好看一
点。 请把它换成你自己的图标。
index.html
这是别人访问你的网站是看到的主页面的
HTML 文件。 大多数情况下你都不用编辑
它。 在构建应用时,CLI会自动把所有 js
和 css 文件添加进去,所以你不必在这里手
动添加任何 <script> 或 <link> 标签。
main.ts
这是应用的主要入口点。 使用 JIT compiler
编译器编译本应用,并启动应用的根模块
AppModule ,使其运行在浏览器中。 你还
可以使用 AOT compiler 编译器,而不用修
改任何代码 —— 只要给 ng build 或 ng
serve 传入 --aot 参数就可以了。
polyfills.ts
不同的浏览器对 Web 标准的支持程度也不
同。 填充库(polyfill)能帮我们把这些不
同点进行标准化。 你只要使用
core-js 和 zone.js 通常就够了,不过你
也可以查看浏览器支持指南以了解更多信
息。
styles.css
这里是你的全局样式。 大多数情况下,你
会希望在组件中使用局部样式,以利于维
护,不过那些会影响你整个应用的样式你还
是需要集中存放在这里。
test.ts
这是单元测试的主要入口点。 它有一些你
不熟悉的自定义配置,不过你并不需要编辑
这里的任何东西。
tsconfig.{app|spec}.json
TypeScript 编译器的配置文件。
tsconfig.app.json 是为 Angular 应用准
备的,而 tsconfig.spec.json 是为单元
测试准备的。
五、Hello Angular 4.0 以及 app.module.ts 、 组件分析
1. app.module.ts
定义 AppModule,这个根模块会告诉 Angular 如何组装该应用。 目前,它只声明了
AppComponent。 稍后它还会声明更多组件。
//Angular 模块类描述应用的部件是如何组合在一起的。 每个应用都至少有一个 Angular 模块,也就
是根模块,
// 用来引导并运行应用。 你可以为它取任何名字。常规名字是 AppModule。 也就是 app.module.ts
文件
/*引入组件*/
import { BrowserModule } from '@angular/platform-browser'; /*BrowserModule,浏览器解
析的模块*/
import { NgModule } from '@angular/core'; /*angualrjs 核心模块*/
import { FormsModule } from '@angular/forms'; /*表单数据绑定 表单验证需要的模块*/
import { HttpModule } from '@angular/http'; /*数据请求模块*/
import { AppComponent } from './app.component'; /*根组件*/
/*@NgModule 装饰器将AppModule 标记为 Angular 模块类(也叫 NgModule 类)。
@NgModule 接受一个元数据对象,告诉 Angular 如何编译和启动应用。*/
@NgModule({
declarations: [ /*引入当前项目运行的的组件*/
AppComponent
],
imports: [ /*引入当前模块运行依赖的其他模块*/
BrowserModule,
FormsModule,
HttpModule
],
providers: [], /*定义的服务 回头放在这个里面*/
bootstrap: [AppComponent] /* 指定应用的主视图(称为根组件) 通过引导根 AppModule 来启动
应用 ,这里一般写的是根组件*/
})
/*根模块不需要导出任何东西, 因为其它组件不需要导入根模块。 但是一定要写*/
export class AppModule { }
2. 自定义组件
https://github.com/angular/angular-cli
创建组件:
ng g component components/header
组件内容 详解: :
import { Component, OnInit } from '@angular/core'; /*引入 angular 核心*/
@Component({
selector: 'app-header', /*使用这个组件的名称*/
templateUrl: './header.component.html', /*html 模板*/
styleUrls: ['./header.component.css'] /*css 样式*/
})
export class HeaderComponent implements OnInit { /*实现接口*/
constructor() { /*构造函数*/
}
ngOnInit() { /*初始化加载的生命周期函数*/
}
}

Angular4.x 创建 组件 、绑定数据、绑定属性、
数据循环、条件判断、事件、表单处理、双
向数据绑定
主讲教师:(大地)
合作网站:www.itying.com (T IT 营)
合作网站:www.ionic.wang ( Ionic 中文网 )
目录
一、创建 angualr 组件..................................................................................................... 1
二、angualr4.0 绑定数据 ................................................................................................. 2
三、数据循环 *ngFor.................................................................................................... 3
四、条件判断 *ngIf ...................................................................................................... 4
五、执行事件 (click)=”getData()”................................................................................. 4
六、绑定属性.................................................................................................................. 5
七、表单处理.................................................................................................................. 5
八、双向数据绑定 .......................................................................................................... 5
九、Todolist 功能 ............................................................................................................ 6
建 一、创建 angualr 组件
https://github.com/angular/angular-cli
Scaffold Usage
Component
ng g component my-new-component
指定目录创建 :ng g component components/Footer
Directive
ng g directive my-new-directive
Pipe
ng g pipe my-new-pipe
Service
ng g service my-new-service
Class
ng g class my-new-class
Guard
ng g guard my-new-guard
Interface
ng g interface my-new-interface
Enum
ng g enum my-new-enum
Module
ng g module my-module
创建组件
ng g component components/header
使用组件:
<app-header></app-header>
二、angualr4.0 绑定数据
1. 数据 文本 绑定
{{}}
<h1>
{{title}}
</h1>
2. 绑定 html
this.h="<h2>这是一个 h2 用[innerHTML]来解析</h2>"
<div [innerHTML]="h"></div>
三、 数据循环 *ngFor
1 、*ngFor 普通循环
<ul>
<li *ngFor="let item of list">
{{item}}
</li>
</ul>
2 、循环的时候设置 key
<ul>
<li *ngFor="let item of list;let i = index;">
{{item}} --{{i}}
</li>
</ul>
2. template 循环数据
<ul>
<li template="ngFor let item of list">
{{item}}
</li>
</ul>
四、条件判断 *ngIf
<p *ngIf="list.length > 3">这是 ngIF 判断是否显示</p>
<p template="ngIf list.length > 3">这是 ngIF 判断是否显示</p>
五、执行 事件 (click)=”getData()”
<button class="button" (click)="getData()">
点击按钮触发事件
</button>
<button class="button" (click)="setData()">
点击按钮设置数据
</button>
getData(){ /*自定义方法获取数据*/
//获取
alert(this.msg);
}
setData(){
//设置值
this.msg='这是设置的值';
}
六、绑定属性
<div [id]="id" [title]="msg">调试工具看看我的属性</div>
七、 表单处理
< input type= "text" (keyup)= "keyUpFn($event)"/>
<input type="text" (keyup)="keyUpFn($event)"/>
keyUpFn(e){
console.log(e)
}
八、 双向数据绑定
<input [(ngModel)]="inputValue">
: 注意引入:FormsModule
import { FormsModule } from '@angular/forms';
@NgModule({
declarations: [
AppComponent,
HeaderComponent,
FooterComponent,
NewsComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
使用: :
<input type="text" [(ngModel)]="inputValue"/>
{{inputValue}}
九、 、Todolist 功能
l html 代码
<input type="text" [(ngModel)]='username'>
<button (click)='addData()'>增加</button>
<ul>
<li *ngFor="let item of list">
{{item}}
</li>
</ul>
J Js s 代码
export class TodolistComponent implements OnInit {
list:any[];
username:any;
constructor() {
}
ngOnInit() {
this.list=[];
this.username='';
}
addData(){
alert(this.username);
this.list.push(this.username);
}
}


Angular4.x 创建使用服务
主讲教师:(大地)
合作网站:www.itying.com (T IT 营)
合作网站:www.ionic.wang ( Ionic 中文网 )
目录
一、Angualr CLI 创建服务 ............................................................................................ 1
二、创建服务命令....................................................................................................... 2
三、app.module.ts 里面引入创建的服务 ..................................................................... 2
四、使用的页面引入服务,注册服务 ......................................................................... 3
一、 Angualr CLI 创建服务
https://github.com/angular/angular-cli
Scaffold Usage
Component
ng g component my-new-component
Service
ng g service my-new-service
二、创建服务命令
ng g service my-new-service
创建到指定目录下面
ng g service services/storage
三、app.module.ts 里面引入创建的服务
1.app.module.ts 里面引入创建的服务
import { StorageService } from './services/storage.service';
2. NgModule 里面的 的 providers 里面依赖注入服务
@NgModule({
declarations: [
AppComponent,
HeaderComponent,
FooterComponent,
NewsComponent,
TodolistComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [StorageService],
bootstrap: [AppComponent]
})
export class AppModule { }
四、使用的页面引入服务,注册服务
import { StorageService } from '../../services/storage.service';
constructor(private storage: StorageService) {
}
使用
addData(){
// alert(this.username);
this.list.push(this.username);
this.storage.set('todolist',this.list);
}
removerData(key){
console.log(key);
this.list.splice(key,1);
this.storage.set('todolist',this.list);
}

Angular4.x get post 以及 jsonp 请求 数据
主讲教师:(大地)
合作网站:www.itying.com (T IT 营)
合作网站:www.ionic.wang ( Ionic 中文网 )
目录
一、app.module.ts 注册HTTP JSONP 服务 ....................................................................... 1
二、通过 Http、Jsonp请求数据、不用 RxJs................................................................... 2
三、通过 Http、Jsonp请求数据、使用 RxJs。 ............................................................... 4
一、 、app.module.ts 注册 HTTP JSONP 服务
1. 引入 HttpModule 、JsonpModule
普通的 HTTP 调用并不需要用到 JsonpModule,不过稍后我们就会演示对 JSONP 的支持,
所以现在就加载它,免得再回来改浪费时间。
import { HttpModule, JsonpModule } from '@angular/http';
2.HttpModule 、JsonpModule 依赖注入
@NgModule({
declarations: [
AppComponent,
HomeComponent,
NewsComponent,
NewscontentComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
JsonpModule,
AppRoutingModule
],
providers: [StorageService,NewsService],
bootstrap: [AppComponent]
})
export class AppModule { }
二、通过 Http 、Jsonp 请求数据、用 不用 RxJs
RxJS 是一种针对异步数据流编程工具,或者叫响应式扩展编程;不管如何解释 RxJS 其目标就是异步编程,
Angular 引入 RxJS 为了就是让异步可控、更简单。
app.module.ts 引入并且依赖注入完成以后 , 在需要用到的地方执行下面操作。 。
用 使用 Http 、Jsonp :
1、 、入 在需要请求数据的地方引入 Http
import {Http,Jsonp} from "@angular/http";
2、 、 构造函数内申明:
constructor(private http:Http,private jsonp:Jsonp) { }
3 、对应的方法内使用 http 请求数据
this.http.get("http://www.phonegap100.com/appapi.php?a=getPortalList&ca
tid=20&page=1")
.subscribe(
function(data){
console.log(data);
},function(err){
console.log('失败');
}
);
this.jsonp.get("http://www.phonegap100.com/appapi.php?a=getPortalList&c
atid=20&page=1&callback=JSONP_CALLBACK")
.subscribe(
function(data){
console.log(data);
},function(err){
console.log('失败');
}
);
使用 Post
1. 引入 Headers 、Http 模块
import {Http,Jsonp,Headers} from "@angular/http";
2. 实例化 Headers
private headers = new Headers({'Content-Type': 'application/json'});
3.post 提交数据
this.http
.post('http://localhost:8008/api/test',
JSON.stringify({username: 'admin'}), {headers:this.headers})
// .toPromise()
.subscribe(function(res){
console.log(res.json());
});
三 、通过 Http、 、Jsonp 、 请求数据、用 使用 RxJs 。
需要用到请求数据的地方入 引入 Http 模块 Jsonp 模块,以及 rxjs
RxJS 是一种针对异步数据流编程工具,或者叫响应式扩展编程;可不管如何解释 RxJS 其
目标就是异步编程,Angular 引入 RxJS 为了就是让异步可控、更简单。
大部分 RxJS 操作符都不包括在 Angular 的 Observable 基本实现中,基本实现只包括
Angular 本身所需的功能。
如果想要更多的 RxJS 功能,我们必须 导入 其所定义的库来扩展 Observable 对象, 以下
是 这个 模块所需导入的所有 RxJS 操作符:
1 、 入 引入 Http 、Jsonp 、RxJs 模块
import {Http,Jsonp} from "@angular/http";
import {Observable} from "rxjs";
import "rxjs/Rx";
你可能并不熟悉这种 import 'rxjs/Rx'语法,它缺少了花括号中的导入列表:{...}。
这是因为我们并不需要操作符本身,这种情况下,我们所做的其实是导入这个库,加载并运行其中的脚本,
它会把操作符添加到 Observable 类中。
2 、 构造函数内申明:
constructor(private http:Http,private jsonp:Jsonp) { }
3 、get 请求
this.http.get("http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&p
age=1")
.map(res => res.json()) .subscribe(
function(data){
console.log(data);
}
);
4 、Jsonp 请求
this.jsonp.get("http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page
=1&callback=JSONP_CALLBACK")
.map(res => res.json()) .subscribe(
function(data){
console.log(data);
}
);
http.get 方法中返回一个 Observable 对象,我们之后调用 RxJS 的 map 操作符对返回的数据
做处理。

父子 组件传值@Input @Output @ViewChild
主讲教师:(大地)
合作网站:www.itying.com (T IT 营)
合作网站:www.ionic.wang ( Ionic 中文网 )
目录
一、 父组件给子组件传值 -@Input................................................................................ 1
二、 父子组件传值的方式让子组件执行父组件的方法 .................................................. 2
三、 子组件通过@Output 执行父组件的方法 ................................................................ 4
四、 父组件通过局部变量获取子组件的引用 ,主动获取子组件的数据和方法(一) 5
五、 父组件通过 ViewChild 主动获取子组件的数据和方法 ............................................ 6
一、 父组件给子组件传值 -@Input
1. 父组件调用子组件的时候传入数据
<app-header [msg]="msg"></app-header>
2. 子组件引入 Input 模块
import { Component, OnInit ,Input } from '@angular/core';
3. 子组件中 @Input 接收父组件传过来的数据
export class HeaderComponent implements OnInit {
@Input() msg:string
constructor() { }
ngOnInit() {
}
}
4. 子组件中使用父组件的数据
<h2>这是头部组件--{{msg}}</h2>
二、 父子组件传值的方式让子组件执行父
组件的方法
1. 父组件定义方法
run(){
alert('这是父组件的 run 方法');
}
2 .调用子组件传入当前方法
<app-header [msg]="msg" [run]="run"></app-header>
3. 子组件接收父组件传过来的方法
import { Component, OnInit ,Input } from '@angular/core';
@Input() run:any;
export class HeaderComponent implements OnInit {
@Input() msg:string
@Input() run:any;
constructor() { }
}
4. 子组件使用父组件的方法。
export class HeaderComponent implements OnInit {
@Input() msg:string;
@Input() run:any;
constructor() { }
ngOnInit() {
this.run(); /*子组件调用父组件的 run 方法*/
}
}
三、 过 子组件通过@Output 执行父组件的方
法 法
1. 子组件引入 Output 和 EventEmitter
import { Component, OnInit ,Input,Output,EventEmitter} from '@angular/core';
2. 子组件中实例化 EventEmitter
@Output() private outer=new EventEmitter<string>();
/*用 EventEmitter 和output 装饰器配合使用 <string>指定类型变量*/
3. 子组件通过 EventEmitter 对象 outer 实例广播数据
sendParent(){
// alert('zhixing');
this.outer.emit('msg from child')
}
4. 父组件调用子组件的时候,定义接收事件 , outer 就是子组件的 EventEmitter 对象 outer
<app-header (outer)="runParent($event)"></app-header>
5. 父组件接收到数据会调用自己的 runParent 方法,这个时候就能拿到子组件的数据
//接收子组件传递过来的数据
runParent(msg:string){
alert(msg);
}
四、 父组件通过局部变量获取子组件的引
用 用 ) ,主动获取子组件的数据和方法(一)
1. 定义 footer 组件
export class FooterComponent implements OnInit {
public msg:string;
constructor() {
}
ngOnInit() {
}
footerRun(){
alert('这是 footer 子组件的 Run 方法');
}
}
2. 父组件调用子组件的时候给子组件起个名字
<app-footer #footer></app-footer>
3. 直接获取执行子组件的方法
<button (click)='footer.footerRun()'>获取子组件的数据</button>
五、 父组件通过局部变量获取子组件的引
用 用, 通过 ViewChild 主动获取子组件的数
据和方法
1. 调用子组件给子组件定义一个名称
<app-footer #footerChild></app-footer>
2. 引入 ViewChild
import { Component, OnInit ,ViewChild} from '@angular/core';
3. ViewChild 和刚才的子组件关联起来
@ViewChild('footerChild') footer;
4. 调用子组件
run(){
this.footer.footerRun();
}


Angular4.x 中的 路由
主讲教师:(大地)
合作网站:www.itying.com (T IT 营)
合作网站:www.ionic.wang ( Ionic 中文网 )
目录
一、Angular 命令创建一个配置好路由的项目 ................................................................ 1
二、Angula4.x 在已有的项目中配置路由 ........................................................................ 3
三、Angular routerLink页面跳转 默认跳转路由 ........................................................ 5
四、Angular routerLinkActive 设置 routerLink 默认选中路由............................................ 6
五、路由的动态传值....................................................................................................... 6
六、路由的 js 跳转 .......................................................................................................... 7
七、路由的 js 跳转 get 传值 ........................................................................................... 8
八、父子路由.................................................................................................................. 9
一、Angular 命令 创建 一个配置好 路由的项
目 目
1. 命令创建项目
ng new demo02 –-routing
2. 创建需要的组件
ng g component home
ng g component news
ng g component newscontent
3. 找到 app-routing.module.ts 配置路由
引入组件
import { HomeComponent } from './home/home.component';
import { NewsComponent } from './news/news.component';
import { NewscontentComponent } from './newscontent/newscontent.component';
配置路由
const routes: Routes = [
{path: 'home', component: HomeComponent},
{path: 'news', component: NewsComponent},
{path: 'newscontent/:id', component: NewscontentComponent},
{
path: '',
redirectTo: '/home',
pathMatch: 'full'
}
];
4. 找到 app.component.html 根组件模板置 ,配置 router-outlet 显示动态加载的路由
<h1>
<a routerLink="/home">首页</a>
<a routerLink="/news">新闻</a>
</h1>
<router-outlet></router-outlet>
二、 、Angula4.x 在 在 已 有的项目中配置路由
1. 新建 组件
ng g component home
ng g component news
ng g component newscontent
2. 新建 app-routing.module.ts ,app-routing.module.ts 中引入模块
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
3. app-routing.module.ts 中 中 引入组件
import { HomeComponent } from './home/home.component';
import { NewsComponent } from './news/news.component';
import { NewscontentComponent } from './newscontent/newscontent.component';
3. app-routing.module.ts 中 中 配置组件
const routes: Routes = [
{path: 'home', component: HomeComponent},
{path: 'news', component: NewsComponent},
{path: 'newscontent/:id', component: NewscontentComponent},
{
path: '',
redirectTo: '/home',
pathMatch: 'full'
}
];
4. app-routing.module.ts 中 中块 配置模块 暴露模块
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
5. 在 在 app.module.ts 引入刚才定义的路由
import { AppRoutingModule } from './app-routing.module';
6.app.module.ts 里面的import 注册这个路由模块
imports: [
BrowserModule,
AppRoutingModule
]
7. 找到 app.component.html 根组件模板置 ,配置 router-outlet 显示动态加载的路由
<h1>
<a routerLink="/home">首页</a>
<a routerLink="/news">新闻</a>
</h1>
<router-outlet></router-outlet>
三、 、Angular routerLink 页面跳转 默认跳
转路由
<a routerLink="/home">首页</a>
<a routerLink="/news">新闻</a>
//刚进来路由为空跳转的路由
{
path:'',
redirectTo:'home',
pathMatch:"full"
}
//匹配不到路由的时候加载的组件 或者跳转的路由
{
path: '**', /*任意的路由*/
// component:HomeComponent
redirectTo:'home'
}
四、 、Angular routerLinkActive 设置 routerLink
默认选中路由
<h1>
<a routerLink="/home" routerLinkActive="active">首页</a>
<a routerLink="/news" routerLinkActive="active">新闻</a>
</h1>
.active{
color:red;
}
五、路由的动态传值
1. 配置动态路由
const routes: Routes = [
{path: 'home', component: HomeComponent},
{path: 'news', component: NewsComponent},
{path: 'newscontent/:id', component: NewscontentComponent},
{
path: '',
redirectTo: '/home',
pathMatch: 'full'
}
];
2. 获取动态路由的值
import { Router, ActivatedRoute, Params } from '@angular/router';
constructor( private route: ActivatedRoute) {
}
ngOnInit() {
console.log(this.route.params);//
this.route.params.subscribe(data=>this.id=data.id);
}
的 六、路由的 js 跳转
1. 引入
import { Router } from '@angular/router';
2. 初始化
export class HomeComponent implements OnInit {
constructor(private router: Router) {
}
ngOnInit() {
}
goNews(){
// this.router.navigate(['/news', hero.id]);
this.router.navigate(['/news']);
}
}
3. 路由跳转
this.router.navigate(['/news', hero.id]);
的 七、路由的 js 跳转 get 传值
1. 引入 NavigationExtras
import { Router ,NavigationExtras,ActivatedRoute} from '@angular/router';
2. 定义一个 goNewsContent 方法 执行跳转 ,用 用 NavigationExtras 配置传参。 。
goNewsContent(){
let navigationExtras: NavigationExtras = {
queryParams: { 'session_id': '123' },
fragment: 'anchor'
};
this.router.navigate(['/news'],navigationExtras);
}
3. 获取 get 传值
constructor(private route: ActivatedRoute) {
console.log(this.route.queryParams);
}
八、父子路由
1. 创建组件引入组件
import { NewsaddComponent } from './components/newsadd/newsadd.component';
import { NewslistComponent } from './components/newslist/newslist.component';
2. 配置路由
{
path: 'news',
component:NewsComponent,
children: [
{
path:'newslist',
component:NewslistComponent
},
{
path:'newsadd',
component:NewsaddComponent
}
]
}
3. 父组件中定义 router-outlet
<router-outlet></router-outlet>

猜你喜欢

转载自www.cnblogs.com/skorzeny/p/8848591.html