新建路由页面
// ①在app-routing.module.ts中引入并注入到routes中:import {GoodsManageComponent} from './goods-manage/goods-manage.component';const routes: Routes = [...{path: 'goods-manage', component: GoodsManageComponent} // goods-manage页面];// ②浏览器中输入:xxxx/#/goods-manage
子组件和父组件传值
// 先引入import { Component, Input, Output, EventEmitter } from '@angular/core';// 子组件:// html文件:<div class="item" (click)="onSonMethod(info)"></div>// ts文件:@Input() sonShuXing:string='这是子属性';@Output() sonMethod = new EventEmitter<any>()onSonMethod(info) {this.sonMethod.emit(info)}// 父组件:// html文件:<app-son [sonShuXing]='接收子属性' (sonMethod)='fatherMethod($event)'><app-son>// ts文件:fatherMethod(info) {console.log(info)}
路由跳转以及传参
// ① 跳转传参:import { Router } from '@angular/router';constructor( private router: Router /** 路由跳转 */ ) { }// 跳转onEditItem(data): void {this.router.navigate(['/group-edit'], {queryParams: {id: data.id}});}// ② 接收:import { ActivatedRoute } from '@angular/router';constructor( public activeRoute: ActivatedRoute ) { }// 接收值ngOnInit() {this.activeRoute.queryParams.subscribe(params => {this.groupId = params.id;console.log(this.groupId);});}
管道
日期管道
// ①ts中使用import { DatePipe } from '@angular/common';constructor( private datePipe: DatePipe ) { };dateTime = this.datePipe.transform(this.upTimeChild.date, 'yyyy-MM-dd HH:mm:ss'),// ②html中使用{{ data.createTime | date:'yyyy-MM-dd HH:mm:ss' }}
自定义管道
自定义管道没必要在ts中使用,管道归根到底就是一个方法,写到utils就好了。
// 命令:ng g p pipe/test-pipe/test-pipe// 生成后会自动注入到根的app.module.ts中,但是一般会选择集成,// pp.module.tsimport { PipePipe } from './pipe/test-pipe/test-pipe';@NgModule({declarations: [...PipePipe],imports: [...],providers: [...],bootstrap: [AppComponent]})// test-pipe.pipe.ts@Pipe({name: 'testPipe' // 使用的pipe名称})transform(value: boolean): any {// 你想要做的处理。参数value就是需要做管道处理的数据}// html中使用<div>{{ someData | testPipe }}</div>
Directive指令
内置指令
属性指令[ngClass]/[ngStyle]、内置结构指令ngIf/ngFor 、[ngSwitch]ngSwitchCasengSwitchDefault等…
<!-- 如 -->import { Component } from '@angular/core';@Component({selector: 'ngstyle-example',template: `<ul *ngFor="let person of people"><li [ngStyle]="{'color': getColor(person.country)}">{{ person.name }} ({{person.country}})</li></ul>`/** 等同于* <ul *ngFor="let person of people">* <li [style.color]="getColor(person.country)">* {{ person.name }} ({{person.country}})* </li>* </ul>*/})export class NgStyleExampleComponent {getColor(country: string) {switch (country) {case 'CN':return 'red';case 'USA':return 'blue';case 'UK':return 'green';}}people: any[] = [{name: "Semlinker",country: 'CN'},{name: "Donald John Trump",country: 'USA'},{name: "Daniel Manson",country: 'UK'}];}
自定义属性指令
1、指令实现
import {Directive, Input, ElementRef, Renderer, HostListener} from "@angular/core";@Directive({selector: '[exeBackground]'})export class ExeBackgroundDirective {private _defaultColor = 'yellow';@Input('exeBackground')backgroundColor: string; // 输入属性,用于设置元素的背景颜色constructor(private elementRef: ElementRef, private renderer: Renderer) {this.setStyle(this._defaultColor);}@HostListener('click') // 这里对应DOM的原生方法onClick() { // 监听宿主元素的点击事件,设置元素背景色this.setStyle(this.backgroundColor || this._defaultColor);}private setStyle(color: string) { // 调用renderer对象提供的API设置元素的背景颜色this.renderer.setElementStyle(this.elementRef.nativeElement,'backgroundColor', color);}}
2、指令应用
import { Component } from '@angular/core';@Component({selector: 'my-app',template: `<h1 [exeBackground]="'red'">Hello {{name}}</h1>`,})export class AppComponent {name = 'Angular';}
自定义结构指令
1、指令实现
import {Directive,Input,TemplateRef, // 用于表示内嵌的 template 模板元素,通过 TemplateRef 实例,我们可以方便创建内嵌视图(Embedded Views),且可以轻松地访问到通过 ElementRef 封装后的 nativeElement。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) {}}
2.指令应用
import { Component } from '@angular/core';@Component({selector: 'my-app',template: `<h1 [exeBackground]="'red'" *exeUnless="condition">Hello {{name}}</h1>`,})export class AppComponent {name = 'Angular';condition: boolean = false;}
loadChildren路由懒加载
1、首先创建需要懒加载的路由模块
//在命令行输入: ng g module loadChild/ --routing=true/** 该语句会在根目录生成loadChild文件夹;* 并在该文件夹下生成load-child-routing.module.ts与load-child.module.ts两个文件;* 其中load-child.module.ts是需要懒加载页面指向的module;* 而load-child-routing.module.ts里面包含具体懒加载的页面。*/// 在load-child.module.ts你会看到:import { NgModule } from '@angular/core';import { LoadChildRoutingModule } from './load-child-routing.module';@NgModule({declarations: [],imports: [LoadChildRoutingModule]})export class LoadChildModule { }
2、然后创建需要懒加载的页面
// 在命令行输入: ng g c loadChild/child// 然后会在loadChild文件夹下生成child文件夹,该文件夹包含该路由页面的html、ts、css以及测试文件// 生成之后,该组件会自动被加入到load-child.module.ts中,所以此时你会看到import { NgModule } from '@angular/core';import { LoadChildRoutingModule } from './load-child-routing.module';import { ChildComponent } from './child/child.component';@NgModule({declarations: [ChildComponent],imports: [LoadChildRoutingModule]})export class LoadChildModule { } /** 这个名称就是要注入的懒加载名称,在loadChildren的路径后面以#注入 8?
3、定义跳转的地址
// load-child-routing.module.tsimport { NgModule } from '@angular/core';import { Routes, RouterModule } from '@angular/router';import { ChildComponent } from "./child/child.component";const routes: Routes = [{path: 'loadChild', component: ChildComponent, // path的值随便你定,就是要跳转的地址}];@NgModule( {imports: [ RouterModule.forChild( routes ) ],exports: [ RouterModule ]} )export class LoadChildRoutingModule { }
4、注入懒加载行为
// 如我想在todolist下做路由懒加载,就在todolist的loadChildren后面注入/** app-routing.module.ts*/import { NgModule } from '@angular/core';import { Routes, RouterModule } from '@angular/router';import { TodoListComponent } from './pages/todo-list/todo-list.component';const routes: Routes = [{ path: 'todolist', component: TodoListComponent },/** 注意:* 当相同的路由下有不同的懒加载模块的时候,* 其不同的懒加载模块里装载的路由页面不能一致,否则重复的路由页面报错无法跳转*/{path: 'todolist',loadChildren:'./loadChild/load-child.module#LoadChildModule' // 注入,注意#后面的就是当前注入路径的ts文件中的名称/** 如果这里的懒加载模块'./loadChild/load-child.module#LoadChildModule'有一个路由页面ChildComponent,* 然后下面的'./loadChild/load-child.module#LoadChildModule'有一个相同的路由页面ChildComponent,* 此时第二个相同的路由页面就会报错。* {* path: 'todolist',* loadChildren:'./loadChild/load-child.module#LoadChildModule'* },*/},]@NgModule( {imports: [ RouterModule.forRoot( routes ) ],exports: [ RouterModule ]} )export class AppRoutingModule { }
5、路由跳转**
// todo-list.component.html<a routerLink='loadChild' class="a">从todolist页面跳转到loadChild页面</a>/** 点击这个路径之后,就会跳转到 /todolist/loadChild 这个页面;* 注意,如果在其他页面跳转到该loadchild页面,路径为完整的 /todolist/loadChild*/
