簡體   English   中英

如何在我的其他組件中排除 app.component.html 的代碼

[英]How to exclude code of app.component.html in my other components

app.component.html是我們的默認組件,其中添加了一個菜單,但我不希望將它包含在我的其他組件中。

我該怎么做?

問題是當我加載newsection.component.html ,它在頂部顯示app.component.html ,如下所示:

在此處輸入圖片說明

我如何限制它以使其不會加載到 editsection.component.html 之上?

您可以結合 Dhyey 和 Hamed Baatour 的回答。

首先,為您的菜單創建一個單獨的組件(例如menu.component.ts )並將您的所有代碼放在那里。

然后修改你的app.component.ts使它看起來像這樣:

<menu-component *ngIf="showMenu"></menu-component>
<router-outlet></router-outlet>

重要提示:現在您必須在app.component.ts設置showMenu不是newsection.component.ts

您可以通過檢查請求的 URL 來完成此操作。 只需像這樣在app.component.ts注入路由器:

constructor(router:Router) {
router.events.forEach((event) => {
    if(event instanceof NavigationStart) {
        this.showMenu = event.url !== "/newsection";
    }
  });
}

如果請求帶有/newsection的路由,則不應顯示菜單。

首先,您應該了解 Angular 的本質,因為它是一個單頁面應用程序,這意味着加載單個 HTML 頁面,您可以使用路由器向其中注入其他代碼。 但是,作為一種解決方法,您可以使用*ngIf指令根據用戶在應用程序中導航的位置來顯示和隱藏您的應用程序組件,如下所示:

if (this.router.url === '/login') {
this.showComponent = false
}

並在您的模板中執行以下操作:

<app-root *ngIf="showComponent" ><app-root>
<router-outlet></router-outlet>

編輯

app-root是您創建的新組件的選擇器,用於將應用程序組件 HTML 和邏輯移入其中。 在您的app.component.html模板中,只需包含我在app.component.ts提供的 HTML 注入路由器並創建名為showComponent的變量,然后在您的ngOnInit或您的構造函數中添加上面的 if 語句以顯示或隱藏app-root組件取決於提供的路由器條件。

如果您只想在少數組件中顯示菜單,則為菜單創建一個新組件,從app.component.html刪除菜單的 html,並將新建的menu組件包含在您想要的文件中,如下所示:

<div id="some-other-component">
    <menu-comp></menu-comp>
    // other html below
</div>

我使用的一個小例子。 變量“title”接收組件位置/路徑。 然后在組件中我檢查:

app.component.ts

isMaps(path) {
    var title = this.location.prepareExternalUrl(this.location.path());
    title = title.slice(1);
    if (path == title) {
        return false;
    }
    else {
        return true;
    }
}

在 app.component.html

   <router-outlet></router-outlet>
    <div *ngIf="isMaps('maps')">
        <app-footer></app-footer>
    </div>

如果組件名稱/路徑是maps ,方法將返回' false '然后在map.component.ts 中不顯示腳

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM