将字符串转换为html元素

时间:2016-12-11 10:04:13

标签: angular typescript

我正在使用angular2项目以及我使用打字稿进行编码。我有服务:

@Component({
    selector: 'my-component',
    templateUrl: 'app/component.template.html'
})

export class MyComponent {

    constructor(public myServie: MyService) {
        this.myServie.get().then((data: any) => {
            // data has html content
        });
    }
}

服务结果如下:

a ='<p>
 <a class="link1" href="#p1">link 1</a>
 <a class="link2" href="#p2">link 2</a>
 <a class="link3" href="#p3">link 3</a>
</p>'

如何在此内容中搜索,找到class =&#34; link1&#34;并更换其href?我不想使用JQuery或类似的东西。

1 个答案:

答案 0 :(得分:1)

<div [innerHtml]="data | safeHtml"></div>

另见In RC.1 some styles can't be added using binding syntax

constructor(
    private elRef:ElementRef, 
    public myServie: MyService,
    private cdRef:ChangeDetectorRef) {
    this.myServie.get().then((data: any) => {
        this.data = data;
        this.cdRef.detectChanges(); // to ensure the DOM is updated
        if(this.isViewInitialized) {
          this.updateHrefs();
        }
    });
}

isViewInitialized = false;
ngAfterViewInit() {
  this.isViewInitialized = true;
  if(this.data) {
    this.updateHrefs();
  }
}

updateHrefs() {
  this.elRef.nativeElement.querySelectorAll('p > a').forEach((e) => { e.href = 'newHref'; });

}