ngRoute模块为AngularJS应用程序提供路由和深层链接服务和指令。
我在我的应用程序中使用材料侧边栏并与路由器导航。基本上看起来像 我在我的应用程序中使用材料侧边栏并与路由器导航。基本上看起来像 <mat-sidenav-container [hasBackdrop]="true" autosize> <mat-sidenav (opened)="openCollapsed()" [opened]="!isMobile" [fixedInViewport]="!isMobile" [fixedTopGap]="64" [fixedBottomGap]="40" [mode]="isMobile ? 'over' : 'side'" > <mat-nav-list> <a *ngFor="let route of routes" mat-list-item (click)="selectNavItem(route.path)" > {{ route.label }}</a > </mat-nav-list> </mat-sidenav> <mat-sidenav-content> <div class="app-result"> <router-outlet></router-outlet> </div> </mat-sidenav-content> </mat-sidenav-container> 基本上是路由和一切工作。但是两个很奇怪 路由显示组件 - 但是我需要单击组件内部以激活它。但是,由于我已经选择了一条路线,如何防止此外单击? i 单击组件 - 侧边栏正在关闭,尽管应保持打开 - 至少在桌面上。在移动设备上,它应该关闭,但我看不出可以在哪里影响这种行为。 fixedInViewport是相应设置的 - 因此没有真正的想法。 我在stackblitz上的项目 当导航触发Navbar关闭时,这将直接显示组件。 selectNavItem(route: string): void { this.router.navigate([route]).then(() => { this.sidenav().close(); }); } 调整大小时,切换仅用于桌面倒塌: ngOnInit() { this.observer.observe(['(max-width: 800px)']).subscribe((screenSize) => { this.isMobile = screenSize.matches; if(!screenSize.matches) { this.isCollapsed = true; } }); } 打开的是在桌面上触发的,该桌面打开了Sidenav,以阻止它,我们可以使用&&并仅在Mobile上触发该功能。 <mat-sidenav-container [hasBackdrop]="true" autosize> <mat-sidenav (opened)="isMobile && openCollapsed()"
I有Angular应用,它使用路由,构建和部署到S3存储桶中。如果我转到应用程序的URL的根源,它可以正常工作。例如www.my-app.com.s3.foo.bar.amazonaws.com/ 它在...
hosameurlnavigation的属性,您可以将其设置为“重新加载”。我已经搜索过它,但是没有很多文章显示该属性的使用。有人可以帮助我一个实时示例,说明我们确切需要在哪里使用该属性。
当独立应用程序中的di routerstate触发nullinjectionorError
我在全新的Angular应用程序中遇到了无原来的错误错误。 我刚刚将此应用程序作为独立的Angular App(NG New AstaloeApp)生成。在AppComponent的构造函数中,我添加了
所以,这几天我一直在练习Angular,在实现延迟加载时遇到了这个问题。我的视频无法加载;如果是,则不会静音,刷新 webp 后...
所以我正在尝试构建 Angular SPA 并希望限制对编辑对话框的访问。我所有的编辑对话框都显示在一个大的模式窗口中。因此,如果用户没有编辑权限,他们
为什么这个路由配置不起作用?路由器正在尝试访问 /posts,但不应访问 /posts。目前它显示一个空白页面。 BlankComponentComponent 包含 router-outlet 和
我有 2 个组成部分:索赔摘要和索赔见解。当我在claims-summary组件中时,url将为http://localhost:4200/claims-summary/claimId/。当我从索赔摘要和 cl 导航时...
我正在尝试在 NgRx Store 中为特定页面设置一些状态(我将导致这些 POI - “感兴趣的页面”)。如果不是这些页面之一,我想将商店设置为默认值....
我想做一个带有密码重置页面的登录页面。在页面中,当我单击“重置密码”时,只有页面的一小部分会发生变化,因此视图将如下所示: 登录页面: <...
我在使用 Angular 的路由导航方法时遇到问题。 我有两个组件:LoginComponent 和 HomeComponent。 当我点击“login.component.html”中的按钮时,我想要重定向...
我在 Github Pages 上托管了一个测试 Angular18 网站。我有一个“关于”页面,可以在本地主机上完美运行,但返回时显示 404 未找到。我按照许多帖子中的建议创建了一个 404.html 文件...
我使用 routerLinkActive 作为选择的默认路由,同时我还显示了图像。初始加载图像不会出现。通过更改选项卡,图像可以正确显示。 下面是我的...
我有一个延迟加载模块,我想始终触发相对于模块根的导航。 但我找不到一种方法来一致地找到模块的根路径。也就是说,如果我的惰性加载
我的侧菜单内容一直存在问题,每当插入 contentId="main-content" 时,导航链接的内容(主页)都不会加载/可见。但是当我删除它时,
Angular 故事书错误:无法匹配任何路线。 URL 段:'iframe.html'
我正在尝试配置故事书项目并收到奇怪的错误。 错误:未捕获(承诺):错误:无法匹配任何路由。 URL 段:'iframe.html' 错误:无法匹配任何路由。 URL 段...
如何有条件地在锚点上使用 [href] 或 [routerLink]?
我需要将相同的锚链接有条件地指向本地或外部资源。我试过 测试 我需要将相同的锚链接有条件地指向本地或外部资源。我试过了 <a [href]="outside?externalUrl:null" [routerLink]="outside?[]:['/route',id]" >test</a> 但这不起作用。我没有收到任何错误,但它指向同一本地页面并忽略外部 URL。有什么想法吗? 另一种选择是构建链接,但我找不到任何文档如何访问服务内的routerLink 编辑:我知道我可以使用 *ngIf 克隆整个链接,但我不想这样做,我的链接包含一个带有很多选项的视频标签 最简单的方法是使用 *ngIf / else: <ng-container *ngIf="outside; else internalBlock"> <a [href]="externalUrl">External</a> </ng-container> <ng-template #internalBlock> <a [routerLink]="['/route', id]">Internal</a> </ng-template> 编辑#1:(丑陋的解决方法) 既然你不想用*ngIf(我还是不明白为什么),你可以这样做: 模板: <a href="javascript:void(0)" (click)="handleClick(outside, '/route', id, externalUrl)">Link</a> 组件: handleClick(outside: boolean, internalUrl: string, internalId: string, externalUrl: string): void { if (outside) { window.location.href = externalUrl; // You can also use Location class of Angular } else { this.router.navigate([`${internalUrl}/${internalId}`]); } } 对于条件 href,在 attr 前面添加。在 href 对我有用之前,使用 null 作为值,如下所示: [attr.href]="!item.subMenu ? item.url : null" 您可以通过在指令中注入 RouterLinkWithHref 来访问 routerLink 实例。 指令: import { ElementRef, Optional, Input, Directive, OnChanges } from '@angular/core'; import { RouterLinkWithHref } from '@angular/router'; @Directive({ selector: '[externalLink]' }) export class ExternalLinkDirective implements OnChanges { @Input() externalLink: string; constructor( private el: ElementRef, @Optional() private link: RouterLinkWithHref ) {} ngOnChanges(){ if (!this.link || !this.externalLink) { return; } this.el.nativeElement.href=this.link.href=this.externalLink; // Replace onClick this.link.onClick = (...args: any[]) => { return true; } } } 用途: <!-- Ignore router link and use external link --> <a routerLink="/some/path" externalLink="https://google.com">Link</a> 对于我的用例,<a>标签内的内容有一些嵌套的html,所以我必须为此创建一个自定义组件。 该组件的作用基本上是 使用内容嵌入 结合上下文使用ngTemplateOutlet 有条件地显示带有 <a> 指令或 routerLink 的 href 标签。 route-or-redirect.component.ts import { Component, ContentChild, Directive, Input, OnInit, TemplateRef, } from '@angular/core'; import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser'; export interface Bookmark { id: string; title: string; imgUrl: string; } @Directive({ selector: '[appLinkContent]', }) export class RouteOrRedirectLinkContentDirective {} @Component({ selector: 'app-router-or-redirect', templateUrl: './router-or-redirect.component.html', styleUrls: ['./router-or-redirect.component.scss'], }) export class RouteOrRedirectComponent implements OnInit { @Input() route = '/'; @Input() set externalLink(link: string) { this.safeUrl = this.sanitizer.bypassSecurityTrustResourceUrl(link); } @Input() redirect = false; @Input() bookmark!: Bookmark; @ContentChild(RouteOrRedirectLinkContentDirective, { read: TemplateRef }) linkContent: TemplateRef<RouteOrRedirectLinkContentDirective> | undefined; safeUrl: SafeResourceUrl | undefined; constructor(private sanitizer: DomSanitizer) {} ngOnInit(): void {} } route-or-redirect.component.html <a [routerLink]="route" *ngIf="!redirect; else redirectLink"> <ng-container *ngTemplateOutlet="linkContent; context: { $implicit: bookmark }" ></ng-container> </a> <ng-template #redirectLink> <a [attr.href]="safeUrl"> <ng-container *ngTemplateOutlet="linkContent; context: { $implicit: bookmark }" ></ng-container> </a> </ng-template> route-or-redirect.component.ts import { Component, OnInit, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { RouterLinkWithHref, RouterModule } from '@angular/router'; import { RouterTestingModule } from '@angular/router/testing'; import { Bookmark, RouteOrRedirectComponent, RouteOrRedirectLinkContentDirective, } from './router-or-redirect.component'; @Component({ selector: 'app-test', template: ` <app-router-or-redirect class="default-no-content"></app-router-or-redirect> <app-router-or-redirect class="default-with-content"> <div *appLinkContent>test link</div> </app-router-or-redirect> <app-router-or-redirect class="use-route" route="/test" externalLink="localhost:4200" > <div *appLinkContent>test link</div> </app-router-or-redirect> <app-router-or-redirect class="use-redirect" route="/test" externalLink="localhost:4200" [redirect]="true" > <div *appLinkContent>test link</div> </app-router-or-redirect> <app-router-or-redirect class="link-with-context" route="/test" externalLink="localhost:4200" [redirect]="true" [bookmark]="bookmark" > <div *appLinkContent="let bookmark"> <img [attr.src]="bookmark.imgUrl" /> <h3>{{ bookmark.title }}</h3> </div> </app-router-or-redirect> `, styles: [], }) export class TestRouterOrRedirectComponent implements OnInit { bookmark: Bookmark = { id: '1', title: 'Test Link', imgUrl: 'https://placeimg.com/640/480/any', }; constructor() {} ngOnInit(): void {} } describe('RouterOrRedirectComponent', () => { let component: TestRouterOrRedirectComponent; let fixture: ComponentFixture<TestRouterOrRedirectComponent>; let defaultWithNoContent: RouteOrRedirectComponent; let defaultWithContent: RouteOrRedirectComponent; let useRoute: RouteOrRedirectComponent; let useRedirect: RouteOrRedirectComponent; beforeEach(async(() => { TestBed.configureTestingModule({ schemas: [CUSTOM_ELEMENTS_SCHEMA], imports: [RouterModule, RouterTestingModule], declarations: [ TestRouterOrRedirectComponent, RouteOrRedirectComponent, RouteOrRedirectLinkContentDirective, ], }).compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(TestRouterOrRedirectComponent); component = fixture.componentInstance; defaultWithNoContent = fixture.debugElement.children[0].componentInstance; defaultWithContent = fixture.debugElement.children[1].componentInstance; useRoute = fixture.debugElement.children[2].componentInstance; useRedirect = fixture.debugElement.children[3].componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should default to link with route point to /', () => { const link = fixture.debugElement .query(By.css('.default-no-content')) .query(By.directive(RouterLinkWithHref)); expect(link).toBeTruthy(); expect(link.attributes.href).toBe('/'); }); it('should default to link with content and route points to /', () => { const link = fixture.debugElement .query(By.css('.default-with-content')) .query(By.directive(RouterLinkWithHref)); expect(link.attributes.href).toBe('/'); expect(link.nativeElement.textContent).toBe('test link'); }); it('should use routerLink for <a> tag if "redirect" binding is not specified', () => { const link = fixture.debugElement .query(By.css('.use-route')) .query(By.directive(RouterLinkWithHref)); expect(link.attributes.href).toBe('/test'); expect(link.nativeElement.textContent).toBe('test link'); }); it('should default "redirect" binding to false', () => { expect(useRoute.redirect).toBe(false); }); it('should use href for <a> tag if "redirect" is true', () => { const link = fixture.debugElement .query(By.css('.use-redirect')) .query(By.css('a')); expect(useRedirect.redirect).toBe(true); expect(link.query(By.directive(RouterLinkWithHref))).toBeNull(); expect(link.nativeElement.href).toBe('localhost:4200'); expect(link.nativeElement.textContent).toBe('test link'); expect(useRoute.redirect).toBe(false); }); it('should use the bound value as the link template context', () => { const link = fixture.debugElement .query(By.css('.link-with-context')) .query(By.css('a')); expect(link.query(By.css('h3')).nativeElement.textContent).toContain( component.bookmark.title ); expect( link.query(By.css('img')).nativeElement.getAttribute('src') ).toContain(component.bookmark.imgUrl); expect(useRoute.redirect).toBe(false); }); }); 经过大量调查,我对这个问题实施了不同的方法,因为我的<a href>...</a>内部包含代码(例如可点击的div)。例如,我不想使用 ngIf,因为这迫使我复制 div 的内部代码。这就是我的解决方案: 组件 HTML <div> <a [href]="getRouterLink()" > <div class="section"> <!-- stuff inside the div --> </div> </a> </div> 组件 JS Component({ selector: 'app-home-section', templateUrl: './home-section.component.html', styleUrls: ['./home-section.component.scss'] }) export class HomeSectionComponent implements OnInit { @Input() link: string; constructor(private router: Router) { } ngOnInit() { } isRouterLink() { if (this.link) { let firstLinkChar = this.link.charAt(0); let isSlash = firstLinkChar == '/'; return isSlash; } return false; } getRouterLink() { let url = this.isRouterLink() ? window.location.origin + this.link : 'http://' + this.link; return url; } } 这是使其工作更简单的唯一方法,因为即使我将“www.example.com”直接放入href(有或没有[ ]),它总是附加基本网址。虽然不漂亮,但是很实用。 [attr.href]="link || null" 我创建了 ngx-href 库,让您可以在需要时使用指令来替换默认的 href 逻辑。 如何使用 奔跑npm install ngx-href 将其添加到您的app.module.ts文件中 import { ngxHrefModule } from 'ngx-href' imports: [ ngxHrefModule.forRoot({}), ], 无论您打算在哪里使用 href 指令 import { ngxHrefModule } from 'ngx-href' imports: [ ngxHrefModule, ] 然后在你的html中 <a href="/angular/router/link"> My internal link </a> // This does also work with button ;) <button href="/angular/router/link"> My internal link </button> 阅读文档了解更多设置 @taras-d 的 directive 不再适用于较新版本的 Angular。 单击链接以更改两个角度屏幕之间的路径后,路由器会擦除 href 而不会触发 ngOnChanges。如果有人想使用指令,我添加了替代解决方案。 如果您仍然想使用指令,我已经修改了他的解决方案。由于它使用 ngDoCheck ,不幸的是它被频繁触发。因此,我添加了一些 if 子句来防止更改过于频繁 @Directive({ selector: '[externalLink]' }) export class ExternalLinkDirective implements DoCheck { @Input() externalLink: string; constructor( private el: ElementRef, @Optional() private link: RouterLinkWithHref ) {} ngDoCheck(){ if(this.externalLink && this.el.nativeElement.href != this.externalLink) { this.el.nativeElement.href = this.externalLink; } if(this.link && this.externalLink != this.link.href) { this.bindHrefToRouter(); } } private bindHrefToRouter() { if(!this.externalLink) {//if externalLink is null/not supplied, nothing to do here return; } if(this.link) { //if a [routerLink] directive was supplied but empty, we force it to follow the deeplink this.link.href = this.externalLink; this.link.onClick = () => { return true; }; }
我有以下路由: //根路由 常量路线:路线= [ { 小路: '', component: AuthenticatedLayoutComponent, //所有子页面都会有标题 孩子们: [ {路径:...