簡體   English   中英

如何通過 Angular 中的 url 更改動態更改類

[英]how to change class dynamically with url change in Angular

我在 app.html 上有一個儀表板組件,我想顯示其中的所有內容,但登錄或注冊 URL 除外。 所以我試圖動態添加/刪除一個定義為main__hidden的類,它使一個塊display: none基於 URL。 但由於某種原因,它不起作用。 我也嘗試在全局 style.css 中定義樣式,但沒有奏效。

應用程序.html

     <app-main *ngIf="showNavbar">
    
      <router-outlet></router-outlet>
    
    </app-main>

應用程序

    export class AppComponent {
      title = 'frontend';
      public showNavbar: boolean = false
    
      constructor(private router: Router) {
        // Removing Sidebar, Navbar, Footer for Documentation, Error and Auth pages
        router.events.forEach((event) => {
          if (event instanceof NavigationStart) {
            if ((event['url'] == '/sign-in') || (event['url'] == '/sign-up')) {
              this.showNavbar = false;
              let body = document.querySelector('body');
              body.classList.add('main__hidden');
            }
          } else {
            this.showNavbar = true;
            let body = document.querySelector('body');
            body.classList.remove('main__hidden');
          }
        });
    
      }
    }

主文件

    .main__header {
      z-index: 1;
      position: fixed;
      background: #22242a;
      padding: 20px;
      width: calc(100% - 0%);
      top: 0;
      height: 30px;
      display: block;
    }
    .main__sidebar {
      z-index: 1;
      top: 0;
      background: #2f323a;
      margin-top: 70px;
      padding-top: 30px;
      position: fixed;
      left: 0;
      width: 250px;
      height: 100%;
      transition: 0.2s;
      transition-property: left;
      overflow-y: auto;
      display: block;
    }
    :host-context(.main__hidden) .main__sidebar {
      display: none;
    }
    
    :host-context(.main__hidden) .main__header {
      display: none;
    }

在 main.ts 中創建一個方法showMain()並在構造函數中調用它

  public showMain = () => {
    this.router.events.forEach((event) => {
      if (event instanceof NavigationStart) {
        if ((event['url'] == '/sign-in') || (event['url'] == '/sign-up')) {
          this.hideMain = false;
          document.querySelector('.main__header').classList.add('main__hidden');
          document.querySelector('.main__sidebar').classList.add('main__hidden');
        } else {
          this.hideMain = true;
          document.querySelector('.main__header').classList.remove('main__hidden');
          document.querySelector('.main__sidebar').classList.remove('main__hidden');
        }
      }
    });
  }``` 

暫無
暫無

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

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