Reputation: 51
I want my anchor tag to redirect on given path, but without reloading the whole web page. My anchor tag looks like below:
<a href="/test" (click)="goHome()">Click me</a>
below is my component in which I am assigning a HTML tag to a variable Htmlsnipet as a string:
@Component({
selector: 'app-form',
templateUrl: './form.component.html',
styleUrls: ['./form.component.scss']
})
export class FormComponent implements OnInit {
htmlSnippet = `<a href="/test">Click me</a>`;
@ViewChild('element') public viewElement: ElementRef;
public element: any;
flag = true
}
and below is the template in which I want that HTML to be rendered as innerHTML
<div>
<span #element [innerHTML] = "htmlSnippet | safe: 'html'"></span>
</div>
all the things are working but when I am clicking on "click me" it is reloading the application.
Upvotes: 3
Views: 8238
Reputation: 31
Use a directive on the element you are calling [innerHtml]
constructor(private elementRef: ElementRef, private router: Router, private renderer: Renderer2) {}
ngOnInit(): void {
setTimeout(() => {
// wait for DOM rendering
this.reinsertScripts();
this.reinsertLinks();
});
}
reinsertLinks(): void {
const links = <HTMLAnchorElement[]>this.elementRef.nativeElement.getElementsByTagName('a');
if (links) {
const linksInitialLength = links.length;
for (let i = 0; i < linksInitialLength; i++) {
const link = links[i];
if (link.host === window.location.host) {
this.renderer.listen(link, 'click', event => {
event.preventDefault();
this.router.navigate([
link.href
.replace(link.host, '')
.replace(link.protocol, '')
.replace('//', '')
]);
});
}
}
}
}
Upvotes: 3
Reputation: 3162
Because you are using href="/test"
, so the browser will recognise it and triggers page load behaviour try to get content from the target path remotely, which is not what you expected obviously.
Instead, you should remove href="/test"
and use routerLink="/test"
, this attribute serves the correct Angular routes.
One more thing, I see you defined a (click)="goHome()"
for this link tag as well, this is confusing and conflict with what you did for trying to specify the route path for this link.
Even though you can have both as you wish but I would suggest keeping either (click)="goHome()"
or routerLink="/test"
.
If you want to do something extra, use goHome()
method and navigate to home screen manually as what Anshuman suggested. Otherwise simply define the route and use routerLink="/test"
.
Upvotes: 3
Reputation: 5462
It seems you are using Angular
. You can use router and navigate to wherever you want.
Add following code in your component. Make sure you have defined route for home (e.g. home
)
// import Router
import {Router} from '@angular/router';
// add in constructor
constructor(private router: Router) {
}
// modify your method goHome as:
goHome() {
this.router.navigate(['/home']);
}
Upvotes: 3