官方文档
在调用 NgAfterViewInit 回调函数以前就会设置这些视图查询。
元数据属性:html
所支持的选择器包括:api
代码:app
<div #testBox [appElementTitle]="'属性指令测试'" [appCopyAttr]="'https://liangyuetian.cn/'"> appElementTitle 属性指令测试 appCopyAttr 属性指令测试 </div> <div #box [appElementTitle]="'这是box的title'" [appCopyAttr]="'https://baidu.com.cn/'"> appElementTitle 属性指令测试 appCopyAttr 属性指令测试 </div>
export class AppComponent implements OnInit, AfterViewInit { @ViewChild('testBox', {read: ElementRef}) elBox: ElementRef; @ViewChild('testBox', {read: CopyAttrDirective}) copy: CopyAttrDirective; @ViewChild('testBox', {read: ElementTitleDirective}) titles: ElementTitleDirective; @ViewChild('box', {read: ElementRef}) elBox2: ElementRef; @ViewChild('box', {read: CopyAttrDirective}) copy2: CopyAttrDirective; @ViewChild('box', {read: ElementTitleDirective}) titles2: ElementTitleDirective; keyUpSearch($event: { [key: string]: any }) { console.log($event.code, $event.key, $event); } ngOnInit() { } ngAfterViewInit() { console.log('one', this.elBox, this.copy, this.titles); console.log('tow', this.elBox2, this.copy2, this.titles2); } }
效果:
函数