Dismiss
Announcing Stack Overflow Documentation

We started with Q&A. Technical documentation is next, and we need your help.

Whether you're a beginner or an experienced developer, you can contribute.

Sign up and start helping → Learn more about Documentation →

I have a directive that i have created in angular2 that changes the innerHTML of a html element. Here is a simple version of the directive

import { Directive, ElementRef, Input, DoCheck } from '@angular/core';

@Directive({
    selector: '[fieldName]'
})

export class FieldNameDirective implements DoCheck {
    element: HTMLElement;

    @Input('fieldName')
    fieldId: number;

    cached: number;

    constructor(
        el: ElementRef,
        private moduleService: ModuleService) {
        this.element = el.nativeElement;
    }

    ngDoCheck() {
        if (this.cached != this.fieldId) {
            // store cached
            this.cached = this.fieldId;
            this.element.innerHTML = 'TEST ME';


        }
    }
}

Now i want to change this directive so that it can contain a routerLink path, something like this

if (this.fieldId == 1)
    this.element.innerHTML = 'NORMAL TEXT';
else
    this.element.innerHTML = '<a routerLink="/path/to/go/to">TEXT WITH LINK</a>';

But doing this doesnt seem to actually generate a href link on the a tag.

In angular1, i think i would need to use the $compile service and compile the HTML for it to work. DO i have to do something similar in angular2,a nd if so how?

I am using the new @angular/router not the deprecated one.

Thanks in advance

share|improve this question

Angular doesn't do anything (except sanitization) for HTML added dynamically.

  • no bindings resolved ([...], (...), xxx="{{...}}
  • no directives or components instantiated
  • no CSS view encapsulation emulation (_ng_content_xxx attributes are not added)

You can use *ngIf to show hide the one element or the other or
you can add components dynamically using ViewContainerRef.createComponent like explained and demonstrated in Angular 2 dynamic tabs with user-click chosen components

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.