After researching this question and implementing a solution that uses NG2's dynamic content loader, I'm stil unable to perform the equivalent of NG1's $compile.
I have some content being served from an API via an HTTP GET. This content already has various directives applied to it.
e.g: <span [ngClass]="{'className': expression}">my content</span>
In my component template, I tried using [innerHTML]="..." which inserts the HTML as expected but of course - it does not compile the directives.
After reading the linked SO question I tried implementing a solution using the dynamic content loader but this also fails. See below:
@Component({
selector: 'child-component',
template: `<span *ngIf="post.content" [innerHTML]="post.content.rendered"></span>`
})
class ChildComponent {
post = <any> [];
slug = <string> '';
gotPost = <boolean> false;
constructor(
private _routeParams: RouteParams,
private _postService: PostService) {
this.slug = _routeParams.get('slug');
this._postService.fetchSinglePost(this.slug).subscribe((e) => {
this.post = this._postService.postSingle;
this.gotPost = true;
});
}
ngOnInit() {
this.post = this._postService.postSingle;
console.log('POST: ', this.post);
}
}
@Component({
selector: 'app-post',
moduleId: module.id,
templateUrl: './post.component.html',
styleUrls: ['./post.component.css'],
directives: [FORM_DIRECTIVES, CORE_DIRECTIVES],
})
export class AppComponent {
slug: string;
post: any;
gotPost: boolean = false;
constructor(
private dcl: DynamicComponentLoader,
private elementRef: ElementRef,
private _routeParams: RouteParams,
private _dcl: DynamicComponentLoader,
private _postService: PostService) {
this.slug = _routeParams.get('slug');
this._postService.fetchSinglePost(this.slug).subscribe((e) => {
this.post = this._postService.postSingle;
this.gotPost = true;
});
}
ngOnInit() {
this.dcl.loadIntoLocation(ChildComponent, this.elementRef, 'child');
}
}
This does get dynamically injected successfully but the directives within the inserted HTML are not parsed/compiled.
How can I get this to compile?