EDIT 1:
Thank you for @Narm for the solution. I got it working!
In let myTemplate = '<div class="test" (tap)="test();">Test</div>';
, I have a tap function.
When I click on it to invoke the function, it does not work and gives an error:
ERROR TypeError: _co.another_test is not a function
Here is what I have so far:
ngOnInit(){
...
let myTemplate = `<div class="test" (tap)="test();">Test</div>`;
...
}
test(){
console.log("Test");
}
Any thoughts?
Original Question Below
From php using REST, I am getting html markup with Angular components:
From php:
function send_html(){
$html = '<div class="test" *ngIf="data">This is an example</div>';
return $html;
};
Then in my angular project, I am trying to add this html dynamically using componentFactoryResolver
: (I understand that it only accepts Angular component)
Here is my though process:
- In
main.ts
(shown below): call thegetDynamicREST()
and get the$html
from php. - When the data is fetched, then send this to
my_component.ts
to make this as an Angular component. - Once the html markup becomes a part of Angular component, then use
createComponent
to create the component.
Of course, it doesn't work...
This is what I have so far: Please feel free to tear it apart.
main.html
<div class="top">
<ng-template #main></ng-template>
</div>
main.ts
import { Component, ViewChild, ComponentFactoryResolver, ViewContainerRef } from '@angular/core';
import { my_component } from './my_component';
@Component({
selector: 'page-main_page',
templateUrl: 'main_page.html'
})
export class main_page {
@ViewChild('main', { read: ViewContainerRef }) entry: ViewContainerRef;
data: any;
constructor(public resolver: ComponentFactoryResolver,
public mine: my_component ){
};
ngOnInit(){
this.getDynamicREST().then((res)=>{
this.mine.data = res;
const factory = this.resolver.resolveComponentFactory(my_component);
this.entry.createComponent(factory);
})
};
}
my_component.ts
import { Component } from '@angular/core';
@Component({
selector: 'my_component ',
template: '<div class="my_component">{{data}}</div>'
})
export class my_component {
data: any;
}
How would I achieve this so that I can fetch angular components dynamically and display them?
Any help will be much appreciated.
Thank you.