0

I'm trying to basically nest components, and I believe it will be easier to explain with the code I have.

Basically I have 2 components, I want to use 1 component in the other in a specific way. Here's how I have them set up:


test.component.ts:

import { Component } from '@angular/core';

@Component( {
    selector: 'test',
    templateUrl: 'partials/test.html'
} )
export class TestComponent {
    constructor() {}
}

another.component.ts:

import { Component } from '@angular/core';
import { TestComponent } from './test.component';

interface Circle {
    show: boolean,
    data: any
}

@Component( {
    selector: 'another',
    directives: [ TestComponent ],
    templateUrl: '/partials/another.html'
} )
export class AnotherComponent {
    circles: Circle[] = [];

    constructor() {
        let testElement = document.createElement( 'test' ),
            defaultCircles = [
                { show: true, data: testElement }
            ];

        this.circles = defaultCircles;
    }
}

partials/another.html:

<ul>
    <li *ngFor="let circle of circles; let i = index">
        {{circle.data}} <!-- this just shows [object HTMLElement] -->
    </li>
</ul>

How can I get it to show the contents of the directive? I tried replacing the data: testElement with data: '<test></test>' and it still doesn't work, it just shows the text <test></test>.

Jared
  • 2,006
  • 4
  • 23
  • 43

2 Answers2

1

This might work:

<ul>
    <li *ngFor="let circle of circles; let i = index" [innerHTML]="circle.data">
    </li>
</ul>
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • With this, it does render it as an HTML element on the page, but the content of `partials/test.html` is not there. – Jared Jul 29 '16 at 15:33
  • 1
    Hard to see what's going from the snippets. Dynamically added HTML doesn't instantiate components or directives nor does it resolve bindings. Angular2 ignores such HTML except passing it through to the browser. You need something like `ViewContainerRef.createComponent()` like demonstrated in http://stackoverflow.com/questions/36325212/angular-2-dynamic-tabs-with-user-click-chosen-components/36325468#36325468 – Günter Zöchbauer Jul 29 '16 at 15:49
0

I ended up following along with the comment on Günter's answer, and came up with this gist that does exactly what I need.

https://gist.github.com/wphax/14570328483baff3d8f79eab675704f2

Jared
  • 2,006
  • 4
  • 23
  • 43