简体   繁体   English

如何在不重新加载 HTML 页面的情况下重定向锚标记链接?

[英]how to redirect anchor tag link without reloading the HTML page?

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:下面是我的组件,其中我将 HTML 标记作为字符串分配给变量 Htmlsnipet:

@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下面是我希望将 HTML 呈现为 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.一切正常,但是当我单击“单击我”时,它正在重新加载应用程序。

It seems you are using Angular .看来您正在使用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 (eg home )确保您已定义回家的路线(例如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']);
}

Use a directive on the element you are calling [innerHtml]在您调用的元素上使用指令 [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('//', '')
            ]);
          });
        }
      }
    }
  }

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.因为您使用的是href="/test" ,所以浏览器会识别它并触发页面加载行为,尝试远程从目标路径获取内容,这显然不是您所期望的。

Instead, you should remove href="/test" and use routerLink="/test" , this attribute serves the correct Angular routes.相反,您应该删除href="/test"并使用routerLink="/test" ,此属性提供正确的 Angular 路由。

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.还有一件事,我看到您也为此链接标签定义了(click)="goHome()" ,这与您尝试指定此链接的路由路径时所做的混淆和冲突。

Even though you can have both as you wish but I would suggest keeping either (click)="goHome()" or routerLink="/test" .即使您可以根据需要同时拥有两者,但我建议保留(click)="goHome()"routerLink="/test"

If you want to do something extra, use goHome() method and navigate to home screen manually as what Anshuman suggested.如果您想做一些额外的事情,请使用goHome()方法并按照 Anshuman 的建议手动导航到主屏幕。 Otherwise simply define the route and use routerLink="/test" .否则只需定义路由并使用routerLink="/test"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM