Angular 4 render html at runtime

1,134 views
Skip to first unread message

Chuck James

unread,
Jul 18, 2017, 12:48:42 PM7/18/17
to Angular and AngularJS discussion
Hi All,

 I am appending 'template html' to a base div. And then try to access this template with variable. but it throwing the error as it's  added 'template html' to DOM but not rendered it to assign the variable to angular eco system. So is there a way to render it, like some renderer API or something to render the string and assign angular (#id) references to angular. 

some code would be easier to understand:


@ViewChild('#cardtempbase', { read: ViewContainerRef }) cardtempbase;
const tempalteDiv = '<ng-template #cardtempbase > </ng-template>';
this.base.nativeElement.insertAdjacentHTML('afterbegin', tempalteDiv);
this.cardtempbase.clear(); // this is throwing as cardtempbase not defined.
this.cardtempbase.createComponent(factory); this is throwing as cardtempbase not defined.



let me know if there is any confusion. 

Thanks,
Chuck

Stéphane Ancelot

unread,
Jul 26, 2017, 8:43:27 AM7/26/17
to Angular and AngularJS discussion
It sounds to me like adding a new component in which your template is defined.

  let factory = this.componentFactoryResolver.resolveComponentFactory(MyNewcomponent);
  let x = this.cardtempbase.createComponent(factory);

your constructor :
// `ViewContainerRef` from the component itself
  constructor(private viewContainerRef:ViewContainerRef, private componentFactoryResolver: ComponentFactoryResolver) {}


in order to work, MyNewComponent must be declared in NgModule (app.module.ts)
entryComponents : [ MyNewComponent ],
Reply all
Reply to author
Forward
0 new messages