首页 > 解决方案 > 如何从 Angular 6 中的另一个组件的打字稿中激活和停用组件中的样式?

问题描述

我在我的app.component.ts

this.renderer.listenGlobal('window', 'scroll', (event) => {
            const number = window.scrollY;
            if ((number > 150 || window.pageYOffset > 150) && this.location.prepareExternalUrl(this.location.path()) == '/') {
                // I want to activate here style .nav-item .nav-link:not(.btn) in navbar.component.html
                navbar.classList.remove('navbar-transparent');
            } else {
                // I want to deactivate here style .nav-item .nav-link:not(.btn) in navbar.component.html
                navbar.classList.add('navbar-transparent');
            }
        });

navbar.component.html我有

<li class="nav-item" *ngIf="!isDocumentation() && !isMain() && !isCloud() && !isView()">
          <a class="nav-link" rel="tooltip" title="Follow us on Twitter" data-placement="bottom"
             href="https://example-link.com" target="_blank">
            <i class="fa fa-twitter"></i>
            <p class="d-lg-none">Twitter</p>
          </a>
        </li>

我想自动激活和停用样式navbar.component.scss

  .nav-item .nav-link:not(.btn){
      color: black;
      border-color: black;
  }

app.component.ts这个地方

        // I want to activate here style .nav-item .nav-link:not(.btn) in navbar.component.html
        navbar.classList.remove('navbar-transparent');
    } else {
        // I want to deactivate here style .nav-item .nav-link:not(.btn) in navbar.component.html
        navbar.classList.add('navbar-transparent');
    }

有什么想法我该怎么做?

标签: htmlcssangulartypescriptangular6

解决方案


我认为您正在寻找的是 ngClass。

在 html 中:

<inptut [ngClass]="'navbar-transparent', boolean" />

这将做的是在布尔值为真时添加样式,并在布尔值为假时将其删除。如果您使用的是父子结构,您可以使用@Input 或@Output 来设置布尔值。否则,您可以使用共享服务。

来源:https ://angular.io/api/common/NgClass https://angular.io/guide/component-interaction


推荐阅读