创建组件命令
ng generate component XXX'组件名字'
ng g c '组件名称'
基本语法
import { Component,OnInit } from '@angular/core';
@Component({
selector: 'app-myc02',
templateUrl: './myc02.component.html',
styleUrls: ['./myc02.component.css']
})
export class Myc02Component implements OnInit {
constructor(){
}
ngOnInit(): void {
}
}
<h2>Products</h2>
<div *ngFor="let product of products">
<h3>
<a [title]="product.name + ' details'">
{{ product.name }}
</a>
</h3>
<p *ngIf="product.description">
Description: {{ product.description }}
</p>
<button (click)="share()">
Share
</button>
</div>
<div [ngSwith]="值">
<! 都没满足时候默认 可以多个同时展示>
<pre *ngSwitchDefault>ng generate component xyz</pre>
<pre *ngSwitchCase="'符合值'">ng add @angular/material</pre>
<pre *ngSwitchCase="'符合值'">ng add @angular/pwa</pre>
<pre *ngSwitchCase="'符合值'">ng add _____</pre>
<pre *ngSwitchCase="'符合值'">ng test</pre>
<pre *ngSwitchCase="'符合值'">ng build
</e>
</div>
子组件给父组件传值
先给父组件定义事件
showData(msg: '') {
console.log('msg', msg);
}
再在父组件定义事件渠道
<app-children-data (msgEvent)="showData($event)"></app-children-data>
msgEvent代表传递给子组件的事件名
子组件通过@output接收
@Output() msgEvent = new EventEmitter();
传递过来的事件名
使用
<button (click)="msgEvent.emit('红红')">喜欢红红</button>
双向绑定
父给子传值@Input
<app-children-data [age]="19" firstName="小明" [boss]="{name:'小亮',age:33,sex:'男'}"></app-children-data>
就像vue v-bind把属性放在子组件上
子组件通过@Input XXX传递过来的名字
直接使用
自定义指令
增加自定义指令
ng generate directive 指令名
ng g d 指令名
做一个获取焦点指令
import { Directive, ElementRef } from '@angular/core';
@Directive({
selector: '[appFocus]',
})
export class FocusDirective {
constructor(e: ElementRef) {
console.log(e);
let input = e.nativeElement;
input.focus();
}
}
管道
内置管道

例如
<li>大写{{'hello'|uppercase}}</li>
<li>首字母大写{{'name is zhang xue'| titlecase}}</li>
<li>百分数{{0.555555|percent:'2.2'}}</li>
//percent第一个值整数个数,第二个小数点后的数(四舍五入)
生成自定义管道
命令
ng g p 管道名
使用
import { Pipe, PipeTransform } from '@angular/core'
@Pipe({
name: 'sixChange',
})
export class SixChangePipe implements PipeTransform {
transform(value: number, lang: string = 'zh'): any {
// return value == 0 ? '男' : '女'
if (lang == 'zh') {
if (value == 0) return '男'
if (value == 1) return '女'
} else if (lang == 'en') {
if (value == 0) return 'man'
if (value == 1) return 'woman'
}
}
}
<h1>自定义管道</h1>
<table border="1">
<thead>
<th>序号</th>
<th>名字</th>
<th>性别</th>
<th>性别</th>
</thead>
<tbody>
<tr *ngFor="let i of pipiData;let in = index">
<td>{{in+1}}</td>
<td>{{i.name}}</td>
<td>{{i.sex|sixChange}}</td>
<td>{{i.sex|sixChange:'en'}}</td>
</tr>
</tbody>
</table>
pipiData = [
{ name: '小明', sex: 0 },
{ name: '小红', sex: 1 },
{ name: '小亮', sex: 0 },
]
ts回顾
class demo {
public aa = '1';
protected bb = 2;
private cc = 3;
get a() {
return this.cc;
}
set b(val: number) {
this.cc = val;
}
}
let xx= new demo()
xx.aa
xx.bb
xx.cc
xx.a
xx.b=6
class ddd extends demo{
constructor(){
super()
}
get q(){
return this.bb
}
get f(){
return this.cc
}
}
常用生命周期
constructor:构造方法,组件出生的第一时间触发
ngOnInit:组件中的内容开始初始化
ngAfterContentInit:组件中的数据初始化时触发
ngAfterViewInit:组件上的UI界面初始化时
ngAfterContentChecked:组件上的数据变化时
ngAfterViewChecked:组件上的UI随着数据变化而更新
ngOnDestroy:组件销毁
服务
命令行
ng generate service xxx
ng g s xxx
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class NameService {
name = ['小明', '小红', '小亮'];
movies = ['八百', '僵尸世界大战', 'spiderMan'];
constructor() {}
}
import { Component } from '@angular/core';
import { NameService } from './name.service';
@Component({
selector: 'app-serve',
templateUrl: './serve.component.html',
styleUrls: ['./serve.component.css'],
})
export class ServeComponent {
names: NameService;
constructor(names: NameService) {
this.names = names;
}
ngOnInit() {
}
}
constructor(public names: NameService){}
网络请求
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Component } from '@angular/core';
@Component({
selector: 'app-http-api',
templateUrl: './http-api.component.html',
styleUrls: ['./http-api.component.css'],
})
export class HttpApiComponent {
res: any;
constructor(public httpApi: HttpClient) {}
ngOnInit() {
console.log(this.httpApi);
this.httpApi.get('').subscribe((res) => {
this.res = res;
});
}
}
路由
路由基础配置
也需要引入import { RouterModule } from '@angular/router';
import { NgModule }from "@langular/core" ;
import { RouterHodule,Routes }from "@angular/router " ;
import { Homecomponent] from
import {Hellocomponent} from "./hello/hello.component"
//路由配置
const routes: Routes = [
{
path: " ",
component:HomeComponent
{
path: "home" ,
component:HomeComponent,
{
path: "he11o",
component :Hellocomponent,
}
//通配
{
path:
component :HomeComponent
}
@NgModule({
imports: [ RouterModule.forRoot(routes)],
exports:[RouterModule]
)}
路由导航
<a [routerLink]='/home'>home</a>===<router-link to='home'></router-link>
angular vue
<router-outlet></router-outlet> === <router-view></router-view>
嵌套路由
const routes:Routes=[
{
path:'home',
component:XXX组件名,
children:[
{path:'hello',component:xxx}
]
}
]
loadComponent: () =>import('./app.component').then((mod) => mod.AppComponent)
路由传参
query
<a [routerLink]="xxx" [queryParams]="{id:3}" routerLinkActive="类名"></a>
在a标签中添加参数queryParams可以通过this.routerinfo.snapshot.queryParams获取参数
routerLinkActive代表路由是否活跃 活跃时启用类名
import{ActivatedRoute} from '@angular/router'
constructor(private routerinfo:ActivatedRouter){}
ngOnInit(){
this.id=this.routerinfo.snapshot.queryParams['id']
}
params
{
path:'xxx/:id'
}
<a [routerLink]="['/xxx','XXXXXX参数']">xxx</a>
ngOnInit(){
this.routerinfo.params.subscribe((parmas:Params)=>{
this.name=params['name']
})
}
js跳转路由
在ts文件中引入router,并在构造函数中注入,然后通过this.router.navigate()进行跳转
import { Component, OnInit } from '@angular/core';
import { Router} from '@angular/router'
export class ProductComponent implements OnInit {
constructor(
public router: Router
) { }
ngOnInit(): void {
}
goProductDetail() {
this.router.navigate(['/productDetail/', '1234'])
}
goHome() {
this.router.navigate(['/home'])
}
}
query传参
import { Router,NavigationExtras} from '@angular/router';
export class ProductComponent implements OnInit {
constructor(
public router: Router
) { }
ngOnInit(): void {
}
goNews() {
let queryParams: NavigationExtras = {
queryParams:{'aid':123}
}
this.router.navigate(['/news'], queryParams);
}
}608
路由守卫
ng g guard xxxx
ng g g xxxx
import { CanActivateFn, Router } from '@angular/router';
export const authGuard: CanActivateFn = (route, state) => {
let router = new Router();
console.log(state.url);
if (!(state.url == '/login')) {
if (localStorage.getItem('s_t')) {
return true;
}
router.navigate(['/login']);
return false;
} else {
return true;
}
};
path: 'contairpage',
component: ContairPageComponent,
canActivate: [authGuard],