4

I have a directive that I have created in angular2 that changes the innerHTML of an 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 router link 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 doesn't 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 and if so how?

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

georgeawg
  • 48,608
  • 13
  • 72
  • 95
Gillardo
  • 9,518
  • 18
  • 73
  • 141

1 Answers1

4

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

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567