0

This question is somewhat similar to the one that reads the same but it is for Angular 2, How can I use/create dynamic template to compile dynamic Component with Angular 2 the solution presented there is archaic at this point and the methods there don't even exist now. So basically my questions is this.

I am loading HTML from a service, the HTML comes with links like this:

<a routerLink='/content' (click)="loadHTMLData(pageId)">

so to load this properly into a container in my view I need to create a component on the fly and set its templateHTML attribute also dynamically to the received HTML, so that the (click) events work.

My idea was to create this dynamic component so they have an event handler that would trigger an event (@Output) with a notification to be then captured by the host component which in turn would perform another call to the service that returns the HTML and would replace this component for a new one with the new loaded HTML and it would repeat the process for each time a link is pressed in the content.

I have setup the dynamic creation of the component according with the instructions in https://angular.io/guide/dynamic-component-loader, so now I have a dynamic component but I don't know how to load the HTML as its template and have it rendering correctly. (right now the template renders as a string literal)

I tried passing the HTML to a static template using [innerHTML] by first sanitizing it with settings to trust the content, but that didn't work either, the html and styles were interpreted but the links weren't working.

The most relevant code looks like this:

@Component({
  selector: 'app-content-info',
  templateUrl: './content-info.component.html',
  styleUrls: ['./content-info.component.css']
})
export class ContentInfoComponent implements OnInit {
  @Input() info: ContenInfo;

  @ViewChild(ContentInfoDirective,{static:true}) cInfoD: ContentInfoDirective;

  constructor(private componentFactoryResolver: ComponentFactoryResolver) { }

  ngOnInit() {
    this.loadComponent();
  }

  loadComponent() {
    const Item = this.info;
    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(Item.component);

    const viewContainerRef = this.cInfoD.viewContainerRef;
    viewContainerRef.clear();
    const componentRef = viewContainerRef.createComponent(componentFactory);
    (<AdComponent>componentRef.instance).data = Item.data;
  }

}

I adapted this from the Angular documentation site (ad-banner.component.ts), but the standard documentation says nothing on how to add a template dynamically.

So basically what I need to know is how can I inject/insert the HTML template with its (click) events in this dynamic component in Angular 8 to make the events work?

The answer that works will be immediately marked as correct.

Will de la Vega
  • 536
  • 1
  • 5
  • 17

0 Answers0