Sergamers
@Sergamers
front-end

Как реализовать динамический рендеринг view?

Подскажите как скомпилировать это:
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(){
  }
}
  • Вопрос задан
  • 264 просмотра
Решения вопроса 1
Sergamers
@Sergamers Автор вопроса
front-end
Нашел схожий вопрос с реализацией директивы Angular 2 как задать template динамически?
Так же есть пакет для ангуляр 5
Ответ написан
Комментировать
Пригласить эксперта
Ответы на вопрос 1
Например так:

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)
	}
}
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы