一. @ViewChild #name 获取本html页面元素引用
- ElementRef是一个允许直接获取DOM元素的一个类,该类包含一个nativeElement属性。当不允许直接操作原生DOM元素时,该属性值为null。
- Renderer该类包含大量可以用来操作DOM原生的方法。
- ViewChild 是属性装饰器,用来从模板视图中获取匹配的元素。视图查询在 ngAfterViewInit 钩子函数调用前完成,因此在 ngAfterViewInit 钩子函数中,才能正确获取查询的元素。
- 在html中通过注入属性(#名字)添加引用
<input type="text" #myInput>
- 在ts中通过ViewChild获取指定元素
方法一:
import { ViewChild, ElementRef } from '@angular/core';
@ViewChild('myInput') input; ==> @ViewChild('myInput') input: ElementRef;
ngAfterViewInit() {
console.dir(this.input);
}
this.input.nativeElement.focus(); // 获取焦点
方法二:
//触发这个方法就可以通过参数box获取到这个元素
<div #box (click)="fn(box)"></div>
fn(dom){ console.log(dom)}
二. @ViewChild 父组件获取子组件的方法(引用)
子组件CircleComponent中定义了 getColorRedFun(i)方法,父组件中想调用这个方法。
- html中添加标记 #circleComponent
- 使用@ViewChild访问子组件
- ngAfterViewInit()以后才可以访问到获取的子组件
- 就可以通过 this.circleComponent访问子组件中的属性和方法了。(也可以直接在方法中使用 this.自定义引用子组件组件名.方法 的方式使用!)
// --------------html--------------
<page-circle #circleComponent> </page-circle>
// --------------ts--------------
export class HomePage {
@ViewChild("circleComponent")
circleComponent: CircleComponent;
ngAfterViewInit() {
this.circleComponent.getColorRedFun(4);
}
}
栗子2:
import { LiveVideoComponent } from '../../components/live-video/live-video.component';
export class PlayBackModelComponent implements OnInit, AfterViewInit {
//@ViewChild(子组件名称) 随便命名:子组件名称
@ViewChild(LiveVideoComponent) live: LiveVideoComponent;
}
ngAfterViewInit() {
//调用 LiveVideoComponent 内部的 initLiveVideo方法
this.live.initLiveVideo();
}
三. 使用 #name 局部变量获取子组件的引用
// 父组件 html
<li *ngFor="let item of dataSet">
<app-child [names] = "item" (click)="father.childFn()" #father></app-child> //使用模板局部变量 #father 调用子组件的方法
</li>
// 父组件 ts
dataSet = [
{"id":0,"name":"张三"},
{"id":1,"name":"李四"}
]
// 子组件 html
<span>{{names.name}}</span>
// 子组件 ts
@Input() names: any = {}
childFn(){
console.log("我是子类的方法");
}
angular2生命周期钩子函数
- 每个接口都有唯一的一个钩子方法,由接口名加上 ng前缀构成的。比如,OnInit接口的钩子方法叫做ngOnInit。
- 生命周期的顺序:
- ngOnChanges:在ngOnInit之前,当数据绑定输入属性的值发生变化时。
- ngOnInit:在第一次ngOnChanges之后。
- ngDoCheck:每次Angular变化检测时。
- ngAfterContentInit:在外部内容放到组件内之后。
- ngAfterContentChecked:在放到组件内的外部内容每次检查之后。
- ngAfterViewInit:在初始化组件视图和子视图之后。
- ngAfterViewChecked:在妹子组件视图和子视图检查之后。
- ngOnDestroy:在Angular销毁组件/指令之前。
网友评论