}
}
在父组件中,要注意别忘了准备工作,导入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’;
}
}
很简单
-
导入ElementRef,AfterViewInit
-
在constructor中注册 private elementRef:ElementRef
-
在ngAfterViewInit钩子中使用elementRef
-
this.elementRef.nativeElement获取DOM
@ViewChild与ElementRef 结合操作子组件的DOM
================================================================================================
@ViewChild是父组件去访问子组件,ElementRef可以用来操作DOM。那么二者结合使用,父组件就可以操作子组件的DOM。
省略准备工作,核心部分如:
<app-child #child> //子组件打锚点
@ViewChild(‘child’,{ static:true }) eleRef : ElementRef;
//还是在ngAfterViewInit使用
ngAfterViewInit(){
let ele = this.eleRef.nativeElement;
ele.color = ’red’;
}
最后
在面试前我花了三个月时间刷了很多大厂面试题,最近做了一个整理并分类,主要内容包括html,css,JavaScript,ES6,计算机网络,浏览器,工程化,模块化,Node.js,框架,数据结构,性能优化,项目等等。
包含了腾讯、字节跳动、小米、阿里、滴滴、美团、58、拼多多、360、新浪、搜狐等一线互联网公司面试被问到的题目,涵盖了初中级前端技术点。
-
HTML5新特性,语义化
-
浏览器的标准模式和怪异模式
-
xhtml和html的区别
-
使用data-的好处
-
meta标签
-
canvas
-
HTML废弃的标签
-
IE6 bug,和一些定位写法
-
css js放置位置和原因
-
什么是渐进式渲染
-
html模板语言
-
meta viewport原理