haizlin / fe-interview

前端面试每日 3+1,以面试题来驱动学习,提倡每日学习与思考,每天进步一点!每天早上5点纯手工发布面试题(死磕自己,愉悦大家),6000+道前端面试题全面覆盖,HTML/CSS/JavaScript/Vue/React/Nodejs/TypeScript/ECMAScritpt/Webpack/Jquery/小程序/软技能……
http://www.h-camel.com
MIT License
25.04k stars 3.24k forks source link

[angular] 第1877天 请说说在Angular中什么是包含? #5839

Open haizhilin2013 opened 1 month ago

haizhilin2013 commented 1 month ago

第1877天 请说说在Angular中什么是包含?

3+1官网

我也要出题

llccing commented 1 week ago

在Angular中,包含(containment) 通常是指组件之间的父子关系,即一个组件包含(或嵌套)另一个组件。通过包含关系,可以实现组件的复用和结构化应用。

以下是一些具体的包含形式:

1. 直接包含

在模板中直接使用子组件的选择器,这是一种最常见的包含方式。

<!-- app.component.html -->
<app-child></app-child>

2. 使用Angular指令

通过Angular的指令(如ng-templateng-contentng-container)实现动态组件的包含。

2.1 ng-content

ng-content指令用于在父组件中指定一个插槽,子组件的内容将被插入到这个插槽中。

<!-- parent.component.html -->
<app-child>
  <p>这是被插入的内容</p>
</app-child>
<!-- child.component.html -->
<ng-content></ng-content>

2.2 ng-template

ng-template指令用于定义一段模板,通常和ng-containerngIfngFor等指令一起使用,实现动态模板的包含。

<!-- parent.component.html -->
<ng-template #templateRef>
  <p>这是动态包含的内容</p>
</ng-template>

<ng-container *ngTemplateOutlet="templateRef"></ng-container>

3. 动态组件加载

在一些复杂应用中,可能需要在运行时动态加载组件。可以使用ComponentFactoryResolver来实现。

import { Component, ViewChild, ViewContainerRef, ComponentFactoryResolver } from '@angular/core';

@Component({
  selector: 'app-parent',
  template: `<ng-template #container></ng-template>`
})
export class ParentComponent {
  @ViewChild('container', { read: ViewContainerRef }) container: ViewContainerRef;

  constructor(private resolver: ComponentFactoryResolver) {}

  loadChildComponent() {
    const factory = this.resolver.resolveComponentFactory(ChildComponent);
    this.container.createComponent(factory);
  }
}

4. 使用路由

通过Angular路由实现组件的嵌套和包含。

// app-routing.module.ts
const routes: Routes = [
  {
    path: 'parent',
    component: ParentComponent,
    children: [
      { path: 'child', component: ChildComponent }
    ]
  }
];
<!-- parent.component.html -->
<router-outlet></router-outlet>

总结

包含是Angular中组件之间建立层次关系的一种方式,使用包含可以提高组件的复用性和应用的结构化程度。通过上述几种方式,可以灵活地在Angular应用中实现组件的包含。