请教个问题?

来源:7-7 实战对话框(2)

simple8514650

2024-01-01

老师您好!下面通过宿主this.dlHost.viewContainerRef.createComponent(
this.componentFactoryResolver.resolveComponentFactory(AComponent)
);和这个教程中的方式有啥区别?有注意的使用的不同场景吗?
import { Component, ViewChild, ComponentFactoryResolver } from ‘@angular/core’;
import { DlHostDirective } from ‘./dl-host.directive’;
import { AComponent } from ‘./a/a.component’;
@Component({
selector: ‘app-root’,
templateUrl: ‘./app.component.html’,
styleUrls: [’./app.component.css’]
})
export class AppComponent {
title = ‘app works!’;
@ViewChild(DlHostDirective) dlHost: DlHostDirective;
constructor(private componentFactoryResolver: ComponentFactoryResolver) { }

ngAfterViewInit() {
	this.dlHost.viewContainerRef.createComponent(
		this.componentFactoryResolver.resolveComponentFactory(AComponent)
	);
}

}

写回答

1回答

接灰的电子产品

2024-01-02

`viewContainerRef.createComponent` 和 `this.appRef.attachView` 的作用相似,都是用于动态创建组件并将其添加到 Angular 应用中,但它们之间有一些关键的区别。
1. **作用范围:**
   - `viewContainerRef.createComponent` 是将动态创建的组件添加到一个指定的 `ViewContainerRef` 中。 `ViewContainerRef` 代表一个 Angular 视图容器,是一个抽象层,用于管理动态创建的组件在父组件中的位置。
   - `this.appRef.attachView` 则是将组件视图添加到整个 Angular 应用的视图体系中,而不是特定的容器。这种方式相当于把组件嵌入到应用的根级别。
2. **关联性:**
   - `viewContainerRef.createComponent` 会在指定的 `ViewContainerRef` 中创建组件,并且它的生命周期受到这个容器的管理。例如,当包含这个 `ViewContainerRef` 的组件销毁时,其内部创建的动态组件也会被销毁。
   - `this.appRef.attachView` 则是将组件添加到应用的全局视图体系中,这样它的生命周期与应用的生命周期相关联。这意味着该组件将一直存在,直到整个应用被销毁。
3. **使用场景:**
   - `viewContainerRef.createComponent` 通常用于动态创建和管理多个组件,并根据需要在特定位置插入、移动或删除这些组件。
   - `this.appRef.attachView` 则适用于将一个组件嵌入到应用的根级别,或者在整个应用生命周期内只需要创建一次的情况。
具体使用哪种方式取决于你的需求。如果你需要更精细的控制,比如在特定位置动态插入组件,使用 `viewContainerRef.createComponent` 可能更合适。如果你只是简单地想将组件嵌入到应用的根级别,那么 `this.appRef.attachView` 也是一个有效的选择。


1
1
simple8514650
非常感谢!
2024-01-02
共1条回复

Angular 开发拼多多webapp 从基础到项目实战

高仿拼多多WebApp,带你在实战环境中学习Angular

1322 学习 · 451 问题

查看课程