我正在開發一個電子商務應用程式,它的前端是用 Angular 13 制作的。
UI 有一個側邊欄,我不想在產品詳細資訊頁面上顯示它。
為此,app\app.component.ts我有:
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'E-commerce';
constructor(private router: Router) {}
ngOnInit() {}
/**
* Check if the router url contains the specified route
*
* @param {string} route
* @returns
* @memberof AppComponent
*/
hasRoute(route: string) {
return this.router.url.includes(route);
}
}
在app\app.component.html:
<div class="app-wrapper">
<app-navbar></app-navbar>
<div class="container">
<div class="row my-3">
<div *ngIf="!hasRoute('products/show/:id')" class="col-sm-6 col-md-4 col-lg-3">
<app-sidebar class="app-sidebar"></app-sidebar>
</div>
<div class="col-sm-6 col-md-8 col-lg-9">
<router-outlet></router-outlet>
</div>
</div>
</div>
<app-footer class="app-footer"></app-footer>
</div>
問題
由于我一直無法理解的原因,此解決方案失敗,并且側邊欄顯示在應用程式的任何位置。
我究竟做錯了什么?
uj5u.com熱心網友回復:
<div *ngIf="notProductDetails()" class="col-sm-6 col-md-4 col-lg-3">
<app-sidebar class="app-sidebar"></app-sidebar>
</div>
HTML ^^^
constructor() {}
public notProductDetails(): void {
return !window.location.pathname.startsWith('/products/show/');
}
TS
只需使用視窗位置來提取路徑名而不是注入路由器 - 洗掉建構式注入。也不需要在那里傳遞一個 prop 值,因為你只有一個要斷言的字串。
uj5u.com熱心網友回復:
這樣,您只運行一次該值。為了實作這一點,您可以像這樣訂閱路由器事件:
public showBar: boolean = true;
constructor(private readonly router: Router) {
this.router.events
.pipe(filter((event) => event instanceof NavigationEnd))
.subscribe(({ urlAfterRedirects }: NavigationEnd) =>
this.showBar = this.hasRoute(urlAfterRedirects)
);
}
<div *ngIf="showBar" class="col-sm-6 col-md-4 col-lg-3">
<app-sidebar class="app-sidebar"></app-sidebar>
</div>
這樣,您showBar每次導航結束時都會更新該值。
uj5u.com熱心網友回復:
如果有人覺得它有用,這里是我應用于這個問題的最終解決方案:
在app\app.component.ts:
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
title: string = 'E-commerce';
constructor(private router: Router) {}
ngOnInit() {}
routeIncludesNot(route: string) {
return !window.location.pathname.startsWith(route);
}
}
在app\app.component.html我有:
<div class="app-wrapper">
<app-navbar></app-navbar>
<div class="container">
<div class="row my-3">
<div *ngIf="routeIncludesNot('/products/show/')" class="col-sm-6 col-md-4 col-lg-3">
<app-sidebar class="app-sidebar"></app-sidebar>
</div>
<div [ngClass]="routeIncludesNot('/products/show/') ? 'col-sm-6 col-md-8 col-lg-9' : ''">
<router-outlet></router-outlet>
</div>
</div>
</div>
<app-footer class="app-footer"></app-footer>
</div>
在此處查看“現場演示” 。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/477969.html
標籤:javascript 有角度的 角13
