[英]Template in my custom component not working in app.component.html
[英]How to exclude code of app.component.html in my other components
您可以結合 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.