2016-08-24 89 views
3

我有一個指令,我在angular2中創建了一個改變HTML元素的innerHTML。這裏是指令的簡單版本Angular2 - 在改變指令中的innerHTML時動態創建routerLink

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'; 


     } 
    } 
} 

現在我想改變這個指令,以便它可以包含一個路由器鏈路路徑,像這樣

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

但是這樣做似乎並不實際上在a標記上生成href鏈接。

在angular1中,我想我需要使用$compile服務並編譯HTML以使其工作。我是否必須在angular2中做類似的事情?如果是這樣,怎麼辦?

我正在使用新的@angular/router而不是已棄用的那個。

+2

我有類似的情況,你最終怎麼解決它? – yl2015

回答

2

Angular不會爲動態添加的HTML做任何事情(除了衛生處理)。

  • 解決所有的綁定([...](...)xxx="{{...}}
  • 沒有指令或組件實例
  • 沒有CSS視圖封裝仿真(沒有添加_ng_content_xxx屬性)

您可以使用*ngIf顯示隱藏一個元素或其他或
您可以使用ViewContainerRef.createComponent動態添加組件,如解釋nd證明在Angular 2 dynamic tabs with user-click chosen components