在Angular中,子视图是通过在父组件中使用ng-content指令来呈现的。相反,getElementById是一种基于DOM的JavaScript方法,通过给定的id属性查找并返回一个元素。
下面是一个例子,演示了如何使用子视图和getElementById来访问DOM元素:
HTML文件:
父组件
父组件文件:
import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
@Component({
selector: 'app-parent',
template: `
父组件
`,
})
export class ParentComponent implements AfterViewInit {
@ViewChild('myDiv') myDiv: ElementRef;
ngAfterViewInit() {
console.log(this.myDiv.nativeElement);
}
}
子组件文件:
import { Component } from '@angular/core';
@Component({
selector: 'app-child',
template: `
子组件
这里是子组件中的内容。
`,
})
export class ChildComponent {}
在这个例子中,父组件包含了一个ng-content,用于显示子组件的内容。子组件中包含了一个具有id为"myDiv"的div元素,并使用#myDiv来在父组件中引用它。使用@ViewChild装饰器来获取对该元素的引用,并在ngAfterViewInit()生命周期钩子中访问它。
使用getElementById的方式如下:
HTML文件:
父组件
父组件文件:
import { Component, AfterViewInit } from '@angular/core';
@Component({
selector: 'app-parent