1

I'm working angular2 project as well as I'm coding with typescript. I have a service:

@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
        });
    }
}

Service result is like this:

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

How can I search in this content, find element with class="link1" and replace its href? I don't want to use JQuery or something like that.

Artin Falahi
  • 1,101
  • 2
  • 16
  • 34
  • Does data contain `a`? – Akhter Al Amin Dec 11 '16 at 10:09
  • Not sure what angular or typescript allows... but if you don't want to include more libraries, you always have the option of using vanilla JS. Something like this should work fine: document.getElementsByClassName("link1").href="website.com"; https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName – DawnPatrol Dec 11 '16 at 10:10
  • do you compile this ? I mean, does this goes into DOM, if it's not , you'd need to use regex – Milad Dec 11 '16 at 10:14

1 Answers1

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

See also 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'; });

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