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.

2
  • 2
    I have a similar situation, how did you solved it eventually? Commented May 29, 2017 at 9:20
  • A possible option stackoverflow.com/a/49435440/943646 Commented Mar 22, 2018 at 18:04

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.