@ViewChild
和@ViewChildren
从视图DOM查询元素,而@ContentChild
和@ContentChildren
从内容DOM查询元素。
@ViewChildren(WriterComponent)
writers: QueryList<WriterComponent>;
@ContentChildren(WriterComponent)
writers: QueryList<WriterComponent>
在这里我无法理解视图DOM和内容DOM之间的确切区别,请解释一下吗?
答案 0 :(得分:1)
内容DOM定义了指令元素的innerHTML。相反,视图DOM是组件的模板(component.html),不包括嵌套在指令中的任何模板HTML
答案 1 :(得分:0)
位于组件模板内部的children元素称为view children。另一方面,在给定组件的宿主元素的开始和结束标签之间使用的元素称为内容子代。
访问查看子级: View Child Docs
import {ViewChild, ViewChildren, Component, AfterViewInit...} from '@angular/core';
// ...
@Component({
selector: 'todo-app',
template: `...`
})
class TodoAppComponent implements AfterViewInit {
@ViewChild(TodoInputComponent) inputComponent: TodoInputComponent
@ViewChildren(TodoComponent) todoComponents: QueryList<TodoComponent>;
constructor(private todos: TodoList) {}
ngAfterViewInit() {
// available here
}
}
访问子级内容: Content Children Docs
@Component({
selector: 'app-footer',
template: '<ng-content></ng-content>'
})
class FooterComponent {}
@Component(...)
class TodoAppComponent {...}
@Component({
selector: 'demo-app',
styles: [
'todo-app { margin-top: 20px; margin-left: 20px; }'
],
template: `
<content>
<todo-app>
<app-footer>
<small>Yet another todo app!</small>
</app-footer>
</todo-app>
</content>
`
})
export class AppComponent {}
// ... in TodoAppComponent
@Component(...)
class TodoAppComponent implements AfterContentInit {
@ContentChild(FooterComponent) footer: FooterComponent;
ngAfterContentInit() {
// this.footer now points to the instance of `FooterComponent`
}
}
// ...
答案 2 :(得分:0)
让我们说我们有一个名为my-component的组件。
@ViewChild和@ViewChildren会在该组件模板中抓取一些内容,因此将在my-component.component.html文件中包含一个html元素。
@ContentChild和@ContentChildren将使用my-component来获取父组件的括号之间的内容。因此,让我们在parent.component.html中添加以下内容:
<my-component>
<div class="name">Hans</div>
</my-component>
您可以使用@ContentChild和@ContentChildren来获取“ Hans”元素。