Creation:2026-06-22Last update:2026-06-22
将此文档参考到您的 AI 助手ChatGPTClaudeDeepSeekGoogle AI modeGeminiPerplexityMistralGrok
使用您最喜欢的AI助手总结文档,并引用此页面和AI提供商
版本历史
- "添加 usePathname 实用程序"v10.0.02026/6/23
- "初始化历史记录"v8.2.02026/6/22
此页面的内容已使用 AI 翻译。
查看英文原文的最新版本Edit this doc
If you have an idea for improving this documentation, please feel free to contribute by submitting a pull request on GitHub.
GitHub link to the documentationCopy
Copy doc Markdown to clipboard
Angular 集成:usePathname Hook 文档
usePathname hook 返回当前浏览器的路径名(已移除区域设置部分),类型为 Angular 的 Signal<string>。它对于构建感知区域设置的导航非常有用——例如,确定哪个导航项处于活动状态——而无需手动移除区域设置前缀。
在 Angular 中导入 usePathname
typescript
复制代码
复制代码到剪贴板
import { usePathname } from "angular-intlayer";概览
usePathname 读取 window.location.pathname,通过 getPathWithoutLocale 移除区域设置前缀,并在浏览器触发 popstate 事件(后退/前进导航)时更新信号。它使用 Angular 的 DestroyRef 在组件销毁时自动清理事件监听器。
使用
src/app/nav-item.component.ts
复制代码
复制代码到剪贴板
import { Component, input } from "@angular/core";import { usePathname } from "angular-intlayer";@Component({ standalone: true, selector: "app-nav-item", template: ` <a [href]="href()" [attr.aria-current]="pathname() === href() ? 'page' : null" > {{ label() }} </a> `,})export class NavItemComponent { readonly href = input.required<string>(); readonly label = input.required<string>(); readonly pathname = usePathname();}返回值
显示表格的所有内容
在弹窗中打开表格以清晰地查看所有数据
| 类型 | 描述 |
|---|---|
Signal<string> | 包含移除区域设置前缀的当前路径名的 Angular 信号。 |
行为
- 移除区域设置:移除开头的区域设置部分(如
/zh/dashboard→/dashboard)。 - 响应式:在
popstate事件(浏览器的后退 / 前进导航)时自动更新。 - SSR 安全:当
window不可用时返回""。 - 清理:当宿主组件销毁时,通过
DestroyRef.onDestroy移除popstate监听器。
示例
src/app/sidebar.component.ts
复制代码
复制代码到剪贴板
import { Component } from "@angular/core";import { usePathname } from "angular-intlayer";@Component({ standalone: true, selector: "app-sidebar", template: ` <nav> @for (link of links; track link.href) { <a [href]="link.href" [style.font-weight]="pathname() === link.href ? 'bold' : 'normal'" > {{ link.label }} </a> } </nav> `,})export class SidebarComponent { readonly links = [ { href: "/dashboard", label: "仪表板" }, { href: "/settings", label: "设置" }, ]; readonly pathname = usePathname();}相关
useLocale— 当前的区域设置 + 区域设置切换器getPathWithoutLocale— 此 hook 使用的底层实用程序