gpt4 book ai didi

angular - createEmbeddedView 和 createComponent 有什么区别?

转载 作者:太空狗 更新时间:2023-10-29 17:05:51 26 4
gpt4 key购买 nike

我对 createEmbeddedViewcreateComponent 的用例感到困惑,即何时使用哪个。

请提出一些可以说明在“动态创建场景”中使用其中任何一个的合适设置的案例。

最佳答案

请参阅 this workshop on DOM manipulation 或阅读 Working with DOM in Angular: unexpected consequences and optimization techniques,我在其中用示例解释了差异。

这两种方法都用于向组件 View (DOM) 动态添加内容。此内容可以是模板或基于组件的。在 Angular 中,我们通常使用 ViewContainerRef 来操作 DOM。这两种方法都可用:

class ViewContainerRef {
...
createEmbeddedView<C>(templateRef: TemplateRef<C>, context?: C, index?: number): EmbeddedViewRef<C>
createComponent<C>(componentFactory: ComponentFactory<C>, index?: number, injector?: Injector, projectableNodes?: any[][], ngModule?: NgModuleRef<any>): ComponentRef<C>
}

要了解有关操作 DOM 的更多信息,请阅读 Exploring Angular DOM manipulation techniques using ViewContainerRef

创建嵌入式 View

它用于使用 TemplateRef 创建 View 。 TemplateRef 是 Angular 编译器在遇到组件 html 中的 ng-template 标记时创建的。使用此方法创建的 View 称为嵌入 View

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

@Component({
selector: 'my-app',
template: `
<ng-container #vc></ng-container>
<ng-template #tpl>
<h1>Hello, {{name}}</h1>
</ng-template>
`,
styles: ['']
})
export class AppComponent {
name = `Angular! v${VERSION.full}`;

@ViewChild('tpl', {read: TemplateRef}) tpl: TemplateRef<any>;
@ViewChild('vc', {read: ViewContainerRef}) vc: ViewContainerRef;

ngOnInit() {
this.vc.createEmbeddedView(this.tpl);
}
}

Stackblitz demo

*ngIf*ngFor 等所有结构指令都使用这种方法,因为它们都包装在 ng-template 中。例如,对于 *ngIf 代码:

<div *ngIf="data">{{name}}</div>

转化为

<ng-template ngIf="data">
<div>{{name}}</div>

ngIf 指令在内部使用了 createEmbeddedView:

@Directive({selector: '[ngIf]'})
export class NgIf {
private _updateView() {
...
if (this._thenTemplateRef) {
this._thenViewRef =
this._viewContainer.createEmbeddedView(this._thenTemplateRef, this._context);

创建组件

它用于使用 ComponentFactory 创建 View 。当您在模块的 bootstrap 属性中指定一个组件时,它由 Angular 编译器创建,因此编译器会为其生成一个工厂。使用此方法创建的 View 称为 hostview

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

@Component({
selector: 'hello',
template: `<h1>Hello Component!</h1>`,
styles: [``]
})
export class HelloComponent {}

@Component({
selector: 'my-app',
template: `
<ng-container #vc></ng-container>
`,
styles: ['']
})
export class AppComponent {

@ViewChild('vc', {read:ViewContainerRef}) vc: ViewContainerRef;

constructor(private resolver: ComponentFactoryResolver) {}

ngOnInit() {
const factory = this.resolver.resolveComponentFactory(HelloComponent);
this.vc.createComponent(factory);
}
}

Stackblitz demo .

要了解有关宿主视图和嵌入式 View 之间差异的更多信息,请阅读 What is the difference between a view, a host view and an embedded view

关于angular - createEmbeddedView 和 createComponent 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46338790/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com