【问题标题】:how to change class dynamically with url change in Angular如何通过Angular中的url更改动态更改类
【发布时间】:2023-04-05 09:24:01
【问题描述】:

我在 app.html 上有一个仪表板组件,我想显示其中的所有内容,但登录或注册 URL 除外。所以我试图动态添加/删除定义为main__hidden 的类,它根据URL 对display: none 进行阻止。但由于某种原因,它不起作用。我也尝试在全局 style.css 中定义样式,但没有成功。

app.html

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

app.ts

    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.css

    .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;
    }

【问题讨论】:

    标签: angular url routes angular-routing


    【解决方案1】:

    在 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');
            }
          }
        });
      }``` 
    

    【讨论】:

      猜你喜欢
      • 2020-03-12
      • 1970-01-01
      • 2018-04-04
      • 1970-01-01
      • 2019-06-28
      • 1970-01-01
      • 1970-01-01
      • 2019-03-25
      • 1970-01-01
      相关资源
      最近更新 更多