在同一个按钮中使用 routerLink 和(单击) [英] Using routerLink and (click) in same button

查看:39
本文介绍了在同一个按钮中使用 routerLink 和(单击)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是在询问最佳实践.在同一个按钮中使用 routerLink 和(单击)是一个好习惯.

This is asking about a best practice. Is it a good practice to use routerLink and (click) in same button.

<button routerLink="/link" (click)="back()">

因为我们可以将路由导航逻辑放在 back() 方法中,如下所示,

Because we can put the router navigation logic in the back() method, like below,

this.router.navigate(['/link']);

我在这方面的发现是,这个 文章,这不是在谈论要遵循的最佳实践.如果一个比另一个好,你能解释一下原因吗.

All I found regarding this is, this article which was not talking about the best practice to follow. If one is better than the other, can you explain the reason.

推荐答案

以下是一些如何使用 routerLinkclick 的示例,

Following are few examples how you can play around with routerLink and click ,

希望这会有所帮助:

->如果您想重定向到某些页面,您可以随时使用:

-> If you want to redirect to certain pages you can always use this :

<a [routerLink]="['/my-book-listing']"> My Books</a>

->如果你想重定向到一个页面,但想发送一些参数,比如 ID,那么使用 :

-> If you want to redirect to a page but want to send some paramater such as ID then use :

<a [routerLink]="['/my-book-details','3']">Book number 3</a>

->如果有需要发送查询参数来路由的情况,那么你可以使用

-> If there is a case in which you need to send Query params to route then you can use

<a [routerLink]="['/search-this']" [queryParams]="{text:'sam',category:'social'}">Go Search</a>

->如果在导航到页面之前需要代码逻辑那么你需要使用

-> If there is a need of code logic before navigating to the page then you need to use

<button (click)="createBook()">Create Book</button>

createBook(bookData){
   // Create Book logic
   this.router.navigate(['/my-book-listing']);
}

->您也可以使用如下但不是一个好习惯,除非您调用函数来销毁变量或保存页面留下数据

-> You can also use as follows but not a good practice unless you are calling function to destroy variables or save page leaving data

<button (click)="showLoader()" [routerLink]="['/my-book-listing']">Create Book</button>

showLoader(){
  // showLoader logic
}

这篇关于在同一个按钮中使用 routerLink 和(单击)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆