问题描述
当我在Angular中进行开发并创建视图时,我总是使用routerLink从一个视图导航到另一个视图.最近,我看到了用Angular制作的重要页面,这些页面使用href而不是routerLink来路由网站上的视图.我的问题是,什么时候在Angular中使用href代替routerLink方便,为什么?是否给人以为它不是SPA的感觉?
When I develop in Angular and create views, I always use the routerLink to navigate from one view to another. Recently I have seen important pages made in Angular that use href instead of routerLink to route views on the website. My question is, when is it convenient to use href instead of routerLink in Angular and why? Is it to give the feeling that it is not a SPA?
如果是这样,我不理解它,因为它失去了Angular布线的全部潜力.
If so, I do not understand it because it loses the full potential of Angular routing.
一些例子是
https://brandstory.in/
https://www.forbes.com/sites/karstenstrauss/2019/01/22/the-most-sustainable-companies-in-2019/#46dd14376d7d
https://about.google/
https://www.colgate.es/
https://marketingplatform.google.com/intl/es/about/enterprise/
预先感谢
推荐答案
当我们在角度中使用 href 时,应用程序将失去其状态,并且整个应用程序将被重新加载.但是当我们使用 routerlink 时,应用程序的状态保持不变例如.假设您的角度项目中有两个页面/组件分别命名为Second和Third.
When we use href in angular the app loses its state and the entire app gets reloaded. But when we use routerlink the state of the app remains the sameE.g. Let's assume you have two pages/component in your angular project named as second and third.
<div class="nav">
<p>Using "href"</p>
<ul>
<li><a href="/" >1</a></li>
<li><a href="/second" (click)="onClick($event)">2</a></li>
<li><a href="/third">3</a></li>
</ul>
</div>
<hr>
<div class="nav">
<p>Using "routerLink"</p>
<ul>
<li><a routerLink="/">1</a></li>
<li><a routerLink="/second">2</a></li>
<li><a routerLink="/third">3</a></li>
</ul>
</div>
<hr>
<div class="page-content">
<p>Page Content</p>
<router-outlet></router-outlet>
<hr>
<p>Input Field</p>
<app-input></app-input>
</div>
在上面的示例中,如果您在输入字段中键入内容并使用 href 导航进行导航,则该状态将丢失.但是,当您使用 routerlink 导航进行导航时,您将获得该输入文本.
In the above example, if you type something in the input filed and use href navigation to navigate then the state of that will get losses. But when you use routerlink navigation to navigate you will have that input text.
让我们看看屏幕后面会发生什么:-
Let's see what happens behind the screen:-
<li><a href="/second" (click)="onClick($event)">2</a></li>
onClick(event: Event) {
event.preventDefault();
}
如果您阻止 href 的默认操作,则会看到该页面不会重新加载 routerlink 中发生的情况,这仅表示 routerlink 还使用了 href 进行导航,但阻止了其默认行为.
if you prevent the default action of href you will see that page will not get reloaded that what happens in routerlink, this simply means that routerlink also used href for navigation but by preventing its default behaviour.
这篇关于什么时候应该使用href代替Angular中的routerLink?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!