也就是说,@ViewChild 是 父组件 用来 “看” 子组件的。
当ViewChild传入的是子组件ChildComponent,即在父组件中注入子组件,从而获取子组件的属性或方法
childComponent.ts
import { Component } from '@angular/core';
@Component({
selector:'app-child',
templateurl:'bababa',
styleUrls:'bababab',
})
export class ChildComponent{
childFunction(){
console.log('this function is from childComponent');
}
}
parentComponent.ts
import { Component } from '@angular/core';
import { ViewChild } from '@angular/core';
import { ChildComponent } from '..../子组件的目录';
@Component({
selector:'app-parent',
templateurl:'bababa',
styleUrls:'bababab',
})
export class ParentComponent{
@ViewChild(ChildComponent) child : ChildComponent;
parentFunction(){
console.log('this function is from parentComponent')
this.child.childFunction();
}
}
在父组件中,要注意别忘了准备工作,导入ViewChild和子组件
import { ViewChild } from '@angular/core';
import { ChildComponent } from '..../子组件的目录';
此时ViewChild传入的是子组件ChildComponent,以变量child保存
@ViewChild(ChildComponent) child : ChildComponent;
这样就可以大大方方的使用子组件里的方法了。
当ViewChild传入的是字符串,子组件打了锚点,父组件通过锚点位置从而获得子组件的属性或方法
八九不离十,只不过使用子组件ChildComponent时要打锚点做标记,即:
<app-child #child>I am a childComponent
另外,在父组件ParentComponent的ts里是这么写的:
export class ParentComponent{
@ViewChild('child') child : any; //找child这个锚点
parentFunction(){
console.log('this function is from parentComponent')
this.child.childFunction();
}
}
近期在项目中发现:对于@ViewChild的使用,更多的是使用打锚点这种方式。有可能是我接触相关项目不够多,总结的这个规律不一定很具有典型性。
当我在项目实践时,需要去找这些父子组件之间的关系,看到有锚点如:
<app-child #child>I am a childComponent
那么我就知道,此父组件使用了 selector为 app-child 的子组件中的某种属性或方法。那么我再去搜索 app-child,再看回父组件的ts,对比查看,我就能知道父组件到底怎么操作子组件。
=========================================================================
ElementRef也是在我了解@ViewChild时顺带了解的,因为在项目中发现他们二者会结合使用。
ElementRef在我现在的理解,我觉得它是用来操作DOM的,对DOM节点做一些操作,改字体啊,颜色啊,诸如此类的。
看看ElementRef的使用
import { Component, ElementRef, AfterViewInit } from '@angular/core';
export class AppComponent {
constructor(private elementRef: ElementRef) { }
ngAfterViewInit() {
console.dir(this.elementRef.nativeElement.querySelector('div'));
this.elementRef.nativeElement.querySelector('div').style.color='red';
}
}
性能优化
1.webpack打包文件体积过大?(最终打包为一个js文件)
2.如何优化webpack构建的性能
3.移动端的性能优化
4.Vue的SPA 如何优化加载速度
5.移动端300ms延迟
6.页面的重构
所有的知识点都有详细的解答,我整理成了280页PDF《前端校招面试真题精编解析》。