Search code examples
angularangular2-templateangular2-components

Set ng2 component template with variable?


Is it possible to set the template url of an angular2 component with an input variable? The solution below doesn't work because step isn't defined until below the component details. But I am curious if something like this could work?

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

@Component({
    selector: 'demo',
    templateUrl: step;
})
export class demoComponent {
    @Input()
    step: string;
}

and then call it like:

<demo [step]="path/to/template"></demo>

Solution

  • You can use [innerHTML] to bind dynamic HTML. Additionally, Input() won't be set until the component is rendered.

    @Component({
        selector: 'demo',
        templateUrl: `
            <div [innerHTML]="content"></div>
        `;
    })
    export class demoComponent {
        @Input() step: string;
    
        private content: string = '';
    
        ngOnInit () {
            if (this.step === "foo") {
                this.content = "bar";
            }
        }
    }
    

    You may have to explicitly set the markup as safe depending on how you're inserting it, just so you're aware.