What is the difference between createEmbeddedView and createComponent?

I am confused between use cases createEmbeddedViewand createComponent, i.e. when to use which.

Please suggest a few cases that might tell you about the appropriate settings for using any of them in a "dynamic creation script."

+10
source share
1 answer

Watch this DOM manipulation workshop or read Working with the DOM in Angular: Unexpected Implications and Optimization Techniques, where I explain the difference with examples.

(DOM). , . Angular DOM, ViewContainerRef. :

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, DOM ViewContainerRef.

createEmbeddedView

TemplateRef. TemplateRef , ng-template html . , , embedded 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

, *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);

createComponent

ComponentFactory. Angular, bootstrap , . , , 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 .

, : , ?

+26

Source: https://habr.com/ru/post/1686103/


All Articles