0

I'm trying inject multi child component into parent component with ElementRef, but something went wrong when I tried to get child component html

My child component

html: string = '';
constructor(private elementRef: ElementRef) { }
ngAfterContentInit() {
  this.html = this.elementRef.nativeElement;
}

And I want to get that child HTML in my parent component

var textComponent = new TextStepComponent();
console.log(textComponent.html); << child component

How can I do this? or Another way?

All things of what I want is getting HTML of a component in another component

Please help!!

4
  • You can't create a component like that. Look up component factories. Commented Jul 11, 2017 at 3:44
  • @Harangue Thanks! Commented Jul 11, 2017 at 3:49
  • do you add child component dynamically? Commented Jul 11, 2017 at 4:49
  • update the post with your HTML code? Commented Jul 11, 2017 at 4:54

1 Answer 1

0

I resolved my problem by this way:

My parent component:

import { TextStepComponent } from './components/text/text.component';

constructor(
  private viewContainerRef: ViewContainerRef,
  private componentFactoryResolver: ComponentFactoryResolver,
) { }

ngAfterViewInit() {
  const componentFactory = 
   this.componentFactoryResolver.resolveComponentFactory(TextStepComponent);
  const containerRef = 
   this.viewContainerRef.createEmbeddedView(this.dataContainer);
  console.log(containerRef);
  const dynamicComponent = 
   containerRef.createComponent(componentFactory).instance;
  dynamicComponent.data = { content: 'xxx' };
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.