Update: Kindly refer to the response provided by @K-coding, as it offers a more efficient approach than mine!
Here is another less effective approach:
Angular does not compile, so if you add an .html file, you cannot use "Angular" to control it. You need to handle it in JavaScript.
The issue with mixing JavaScript and Angular is that we cannot rely on the function names. Hence, we must dispatch a CustomEvent and subscribe to it.
Let's create a function that retrieves all the "link" elements inside a div called wrapper using a template reference variable.
<div #wrapper>
<div [innerHTML]="link"></div>
</div>
createLinks()
{
//get the "links" inside the "wrapper"
const links = this.wrapper.nativeElement.getElementsByTagName('a');
//for each link
for (var i = 0; i < links.length; i++) {
//we change the color only to check if it works
links[i].style.color = 'red';
//we override the click event
links[i].onclick = (event) => {
//prevent default behavior
event.preventDefault();
//get the "target" using getAttribute('href')
const target = (event.target as HTMLElement).getAttribute('href');
//dispatch a custom event from "wrapper"
this.wrapper.nativeElement.dispatchEvent(
new CustomEvent<string>('route', { detail: target })
);
};
}
}
//and in ngOnInit, we subscribe to the custom event
ngOnInit()
{
fromEvent(this.wrapper.nativeElement, 'route').subscribe((res: any) => {
this.router.navigate([res.detail]);
});
}
}
Here is a simple stackblitz example
NOTE: In the stackblitz, notice that I call the function "createLink" after everything is painted. I use a setTimeout to allow Angular time to render - alternatively, you could use ngAfterViewInit, but when creating the D3 tree, you need to call it after the rendering process.