@viewChildhtml
做用一:选择组件内节点node
<!--视图 --> <div #mydiv><input></div>
// 选择 @ViewChild('mydiv') mydiv: ElementRef // 返回原生节点 let el = this.mydiv.nativeElement // // 使用原生方法 let ipt = el.querySelector('input')
做用二:选择子组件可调用自组件内的函数
子组件:
@Component({ selector: 'user-profile' })
export class UserProfile {
constructor() {}
sendData() { //send data }
}
当前组件
import { Component, ViewChild } from '@angular/core';
import { UserProfile } from '../user-profile';
@Component({ template: '<user-profile (click)="update()"></user-profile>', })
export class MasterPage {
// ViewChild takes a class type or a reference name string.
// Here we are using the type
@ViewChild(UserProfile) userProfile: UserProfile
constructor() { } ngAfterViewInit() {
// After the view is initialized,
this.userProfile will be available this.update();
}
update() {
this.userProfile.sendData();
}
}
@ViewChild 选择组件模板内的节点typescript
@ContentChild 选择当前组件引用的子组件 @ContentChild(组件名)
app
@ViewChildren 和 @ContentChildren 则为对应的复数函数
import { Component, ContentChild, AfterContentInit } from '@angular/core'; import { ChildComponent } from './child.component'; @Component({ selector: 'exe-parent', template: ` <p>Parent Component</p> <ng-content></ng-content> ` }) export class ParentComponent implements AfterContentInit { @ContentChild(ChildComponent) childCmp: ChildComponent; ngAfterContentInit() { console.dir(this.childCmp); } }
import { Component } from '@angular/core'; @Component({ selector: 'exe-child', template: ` <p>Child Component</p> ` }) export class ChildComponent { name: string = 'child-component'; }
import { Component } from '@angular/core'; @Component({ selector: 'my-app', template: ` <h4>Welcome to Angular World</h4> <exe-parent> <exe-child></exe-child> </exe-parent> `, }) export class AppComponent { }
都是属性装饰器ui
都有对应的复数形式装饰器:ContentChildren、ViewChildrenthis
都支持 Type<any>|Function|string 类型的选择器spa
ContentChild 用来从经过 Content Projection 方式 (ng-content) 设置的视图中获取匹配的元素code
ViewChild 用来从模板视图中获取匹配的元素component
在父组件的 ngAfterContentInit 生命周期钩子中才能成功获取经过 ContentChild 查询的元素
在父组件的 ngAfterViewInit 生命周期钩子中才能成功获取经过 ViewChild 查询的元素
// 添加类 this.renderer2.addClass(el, 'active') // 移除了类 this.renderer2.removeClass(el, 'active') // 设置样式 this.renderer2.setStyle(el, 'height', '10px') // 移除样式 this.renderer2.removeStyle(el, 'height') // 设置属性 this.renderer2.setAttribute(el, 'data-id', 'id') // 移除属性 this.renderer2.removeAttribute(el, 'data-id') // 设置值 this.renderer2.setValue(ipt, 'some str') // 监听事件 this.renderer2.listen(el, 'click', (e)=>{console.log(e)}) //el|'window'|'document'|'body' // 其余相似 createElement 建立元素 createComment 动态建立组件 createText 建立文本节点 destroyNode 销毁节点 appendChild 插入子节点 insertBefore (parent: any, newChild: any, refChild: any): void removeChild(parent: any, oldChild: any): void 移除子元素 selectRootElement(selectorOrNode: string|any): any parentNode(node: any): any nextSibling(node: any): any