S
S
Sergey2018-06-02 13:11:31
Angular
Sergey, 2018-06-02 13:11:31

How to implement dynamic view rendering?

Please tell me how to compile this:

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

@Component({
  selector: 'app-root',
  template: '{{comp}}',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  public  title = 'app';

  public comp = '<h1>Скомпилируй</h1> <app-serv-comp></app-serv-comp>';

  constructor(
  ){}

  ngOnInit(){
  }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey, 2018-06-02
@Sergamers

I found a similar question with the implementation of the Angular 2 directive, how to set the template dynamically?
There is also a package for Angular 5

D
Dmitry Luzanov, 2018-06-02
@dmitry_luzanov

For example like this:

import {
  Component,
  ViewChild,
  ViewContainerRef,
  OnInit,
  ComponentFactoryResolver,
  Injector,
  EmbeddedViewRef,
  ElementRef
} from '@angular/core'
import { Type } from '@angular/core'

@Component({
  selector: 'app-root',
  template: '<h1>Скомпилируй</h1> <div #outlet></div>',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  public title = 'app'
        public AnyComponent

  @ViewChild('outlet') outlet: ElementRef

  constructor(
    private readonly factoryResolver: ComponentFactoryResolver,
    private readonly injector: Injector
  ) {}

  public ngOnInit() {
    this.appendComponent(this.AnyComponent)
  }

  public appendComponent<T>(component: Type<T>) {
    const componentRef = this.factoryResolver
      .resolveComponentFactory(component)
      .create(this.injector)

    const domElem = (componentRef.hostView as EmbeddedViewRef<any>)
      .rootNodes[0] as HTMLElement

    this.outlet.nativeElement.appendChild(domElem)
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question