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.

3
  • Does data contain a? Commented Dec 11, 2016 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"; developer.mozilla.org/en-US/docs/Web/API/Document/… Commented Dec 11, 2016 at 10:10
  • do you compile this ? I mean, does this goes into DOM, if it's not , you'd need to use regex Commented Dec 11, 2016 at 10:14

1 Answer 1

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

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

4 Comments

Good idea. but its not working. I'm getting data form remote rest api. So ngAfterViewInit fires before data bound (in constructor).
Sorry, forgot about that. That makes it a bit more complicated. I'm updating my answer.
tnx. It worked. Can i ask why have u used 'a > a'? I'm using 'a'.
Ups, I meant 'p > a' but if there are no other <a> then jsut 'a' will work as well.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.