Angular 教程 - 内容投影、@ContentChild 和 @ViewChild
2024-01-10 13:26:24
正文
引言
我们在上几篇的内容中,学习了组件的基础知识,今天我们带来的是关于组件基础使用的最后一块:内容投影和 @ContentChild、@ViewChild。在组件封装的时候非常有用,我们一起来体验一下。
内容投影
内容投影允许您将组件的内容投射到另一个组件中。这在构建可重用组件时非常有用,例如标题、页脚等。
要使用内容投影,您需要在父组件中使用 <ng-content>
元素。<ng-content>
元素充当占位符,子组件的内容将投射到此占位符中。
例如,我们有一个父组件 AppComponent
和一个子组件 ChildComponent
。AppComponent
中包含 <ng-content>
元素,而 ChildComponent
中包含一些文本内容。
// AppComponent.html
<ng-content></ng-content>
// ChildComponent.html
<h1>Hello World!</h1>
当 ChildComponent
投射到 AppComponent
中时,Hello World!
文本将显示在 AppComponent
中。
@ContentChild 和 @ViewChild
@ContentChild
和 @ViewChild
是两个装饰器,允许您访问组件的子元素。
@ContentChild
用于访问子组件的内容,而 @ViewChild
用于访问组件的子元素。
例如,我们有一个父组件 AppComponent
和一个子组件 ChildComponent
。AppComponent
中包含一个 <ng-content>
元素,而 ChildComponent
中包含一个名为 myInput
的输入元素。
// AppComponent.html
<ng-content></ng-content>
// ChildComponent.html
<input #myInput />
在 AppComponent
中,我们可以使用 @ContentChild
装饰器来访问 ChildComponent
中的 myInput
元素。
// AppComponent.ts
import { Component, ContentChild } from '@angular/core';
@Component({
selector: 'app-root',
template: `<ng-content></ng-content>`
})
export class AppComponent {
@ContentChild('myInput') myInput!: HTMLInputElement;
}
在 ChildComponent
中,我们可以使用 @ViewChild
装饰器来访问 myInput
元素。
// ChildComponent.ts
import { Component, ViewChild } from '@angular/core';
@Component({
selector: 'child-component',
template: `<input #myInput />`
})
export class ChildComponent {
@ViewChild('myInput') myInput!: HTMLInputElement;
}
何时使用内容投影、@ContentChild 和 @ViewChild
内容投影、@ContentChild 和 @ViewChild 在组件封装中非常有用。
您可以使用内容投影来构建可重用组件,例如标题、页脚等。您可以使用 @ContentChild 和 @ViewChild 来访问组件的子元素。
结论
内容投影、@ContentChild 和 @ViewChild 是 Angular 中非常有用的工具。您可以使用它们来构建可重用组件,并访问组件的子元素。这使您可以构建更灵活和可维护的 Angular 应用程序。