I have been trying to apply this code to highlight hyperlinks in content that is fetched from a DB through an API. The code works to apply hyperlink highlighting in the "Description" part, but the same code doesn't highlight hyperlinks for the "Notes" section.
Here is the code:
import { AfterViewInit, Component, Inject, OnInit } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
@Component({
selector: 'app-variable-notes-dialog',
templateUrl: './variable-notes-dialog.component.html',
styleUrls: ['./variable-notes-dialog.component.scss']
})
export class VariableNotesDialogComponent implements OnInit, AfterViewInit {
variableNotes;
pageTitle: string;
constructor(@Inject(MAT_DIALOG_DATA) public data: any, public dialogRef: MatDialogRef<VariableNotesDialogComponent>) {
if(data) {
this.variableNotes = data.variableNotes;
this.pageTitle = data.pageTitle;
}
}
ngOnInit(): void {
}
ngAfterViewInit(): void {
const notes = document.getElementById('notes');
const description = document.getElementById('description')
// notes.innerHTML = this.variableNotes.notes? this.variableNotes.notes: '--';
this.variableNotes.notes ? notes.getElementsByTagName('p')[0].innerHTML = this.variableNotes.notes : notes.classList.add('hidden')
description.innerHTML = this.variableNotes.description? this.variableNotes.description : '--';
description.childNodes?.forEach(node => {
if (node instanceof HTMLAnchorElement) {
node.classList.add('font-bold', 'text-red-600')
}
})
notes.childNodes?.forEach(node => {
if (node instanceof HTMLAnchorElement) {
node.classList.add('font-bold', 'text-red-600')
}
})
}
onClose() {
this.dialogRef.close();
}
}
Here is the output, the problem is that hyperlink "here" is not highlighted in notes while the hyperlink is description is highlighted using the code above:
This is the wrong way to go about this. If you want to programmatically format text in the HTML template, the solution is not to directly manipulate the DOM from the component. The correct thing to do is to use a pipe. You can read about pipes here. There's even an Angular npm package that's a pipe that will do exactly what you want called ngx-linky.