0

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?

Community
  • 1
  • 1
tctc91
  • 1,343
  • 2
  • 21
  • 41
  • Possible duplicate of [How to realize website with hundreds of pages in Angular2](http://stackoverflow.com/questions/36008476/how-to-realize-website-with-hundreds-of-pages-in-angular2) – Günter Zöchbauer Mar 28 '16 at 15:09
  • Usually the answer for dynamically adding components is https://angular.io/docs/ts/latest/api/core/DynamicComponentLoader-class.html. If you can't build your requirements this way, have a look at the link above. – Günter Zöchbauer Mar 28 '16 at 15:11

0 Answers0