angular

284 阅读2分钟

1 属性 []

html
<div [id]="'idname'">{{title}}</div>
<div [class]="['aaa','aaaa']"></div>
<img [src]="itemImageUr">
<div [style.background-color]="expression">我是绑定单一样式</div>
<div [style]="navStyle">我是绑定多样式</div>
navStyle = 'font-size: 20px; color: pink;';

2 指令 *

<ul>
  <li *ngFor="let itme of customers">{{itme.value}}</li>
</ul>

<!--if/else-->
<div *ngIf="ifFlag; else elseBlock">if-</div>
<ng-template #elseBlock> else</ng-template>

3 数据绑定[{}]

<input [ngModel]="obj.name"> //单向
<input [(ngModel)]="obj.name" (input)="inp()" > //双向

4 事件()

<button (click)="deleteHero()">Delete</button>

5 依赖注入 Injectable({providedIn: 'root'})

被引用组件引入Injectable(元数据) 使用@Injectable({providedIn: 'root'})
引用页面可以引入被引用的组件后,可以获取该组件属性方法

概念:
Injectable:标记性元数据,表示一个类可以由 Injector 进行创建
providedIn: 确定哪些注入器将提供可注入。

logger.service.ts文件
import { Injectable } from '@angular/core';

@Injectable({providedIn: 'root'})
export class Logger {
  writeCount(count: number) {
    console.warn(count);
  }
}
import { Component } from '@angular/core';
import { Logger } from '../logger.service';

@Component({
  selector: 'hello-world-di',
  templateUrl: './hello-world-di.component.html'
})
export class HelloWorldDependencyInjectionComponent  {
 
  constructor(private logger: Logger) { }

  onLogMe() {
    this.logger.writeCount(this.count);
  }
}

5 组件传值

1 父传子

父组件中

子组件标签中,自定义属性名是子组件中输入属性@Input()属性

<app-child [fromParentMsg]="fromParentMsg"></app-child>
//ts文件声明变量
fromParentMsg:string="要给子组件传的值"

子组件中

@Input() fromParentMsg: string = ''

@Input():一个装饰器,用来把某个类字段标记为输入属性,并提供配置元数据

2 子传父

子组件中

子组件使用@Output()和 EventEmitter() 的实例定义一个名为 `toParentsMsg` 的属性  

@Output() toParentsMsg= new EventEmitter()
this.toParentsMsg.emit("子要传父的值")

@Output:一个装饰器,用于把一个类字段标记为输出属性,并提供配置元数据

父组件中

<app-child (toParentsMsg)="getChildMsg($event)"></app-child>

//事件接收值
getChildMsg(msg:any){ console.log(msg,"子传父的值") }

3 父组件主动获取子组件属性/方法

<son #tagson></son>
@ViewChild('tagson') tagson
事件内:通过 this.tagson.属性/this.tagson.方法() 就可以了

6 生命周期

指令和组件都有的:
1.ngOnChanges:在 ngOnInit() 之前以及所绑定的一个或多个输入属性的值发生变化时都会调用
2.ngOnInit:在 Angular 第一次显示数据绑定和设置指令/组件的输入属性之后,初始化指令/组件。 在第一轮 ngOnChanges() 完成之后调用,只调用一次。
3.ngDoCheck:当 Angular 把外部内容投影进组件视图或指令所在的视图之后调用。 第一次 ngDoCheck() 之后调用,只调用一次。
4.ngOnDestroy:销毁指令或组件之前立即调用

组件特有:
5、ngAfterContentInit – 在组件内容初始化之后调用
6、ngAfterContentChecked – 组件每次检查内容时调用
7、ngAfterViewInit – 组件相应的视图初始化之后调用
8、ngAfterViewChecked – 组件每次检查视图时调用

顺序12356784,销毁在最后

7路由

1 导航式传参

<button [routerLink]="['/ccc']" [queryParams]="{id:44}">跳转</button>
<button routerLink= '/ccc' [queryParams]="{id:12}">首页</button>

接收--queryParams接收
import {ActivatedRoute} from '@angular/router'
constructor(public route:ActivatedRoute) {}
this.route.queryParams.subscribe((res)=>{
  console.log(res,"p")
})

2 动态路由传值

路由设置
{
  path:'detail/:id',
  component:HeroDetailComponent
},
跳转
<button [routerLink]="[ '/detail/', '1234' ]">动态传参</button>
接收--params接收
route.params.subscribe((e:any)=> {
  console.log(e)
})

3