【问题标题】:Change css attribute by component on init在初始化时按组件更改 css 属性
【发布时间】:2017-04-23 16:51:14
【问题描述】:

我正在使用 Angular 2.4.1,我的最终 Hello World 是下一个:

我的索引由导航栏(显示:无)和一个用于呈现不同视图的路由器插座组成。我的默认视图是带有指向特定视图的链接的轮播。 当我单击此链接时,将加载特定视图并且(这是问题所在),我也想显示导航栏(显示:块)。我被卡住了,我不知道如何实现它。

我的问题是如何从第二个组件到达第一个组件中的导航栏(id,甚至是类)。

我最好的方法是在其组件的 OnInit 中更改此导航栏的 css 属性。不工作... 文档无法识别。

export class SociosComponent implements OnInit {
    ngOnInit(): void {
        this.document.getElementById('nav-principal').style.display = "block";
    }
}

以下是部分代码:

app.component

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
  <ul id="nav-principal" style="display:none; background-color:transparent;" class="nav nav-tabs">
    <li role="presentation" class="active"><a routerLink="/index">Index</a><li>
    <li role="presentation"><a routerLink="/socios">Socios</a><li>
  </ul>
  <router-outlet></router-outlet>
  `
})

export class AppComponent { 
}

app.rounting

// Importar componentes y módulos para el routing 
import { Routes, RouterModule } from '@angular/router';

// Componentes
import { SociosComponent } from './socios.component';
import { Index } from './index';

// Configuración de las rutas
const appRoutes: Routes = [
  { path: '', redirectTo: 'index', pathMatch: 'full' },
  { path: 'index', component: Index },
  { path: 'socios', component: SociosComponent },
];

export const routing = RouterModule.forRoot(appRoutes);

socios.component

import { Component } from '@angular/core';

@Component({
  selector: 'socios',
  templateUrl: '../socios.html',
})

export class SociosComponent implements OnInit {
    ngOnInit(): void {
        this.document.getElementById('nav-principal').style.display = "block";
    }
}

谢谢大家。

【问题讨论】:

    标签: angular


    【解决方案1】:

    像这样直接修改 DOM 元素在 Angular 中被认为是不好的做法。

    正确的做法是将菜单状态存储在服务中,然后从您的组件中对其进行修改。

    菜单状态服务:

    import { Injectable } from '@angular/core';
    
    @Injectable()
    export class MenuStateService {
      isActive: boolean = false;
    
      enable() {
        this.isActive = true;
      }
    
      disable() {
        this.isActive = false;
      }
    }
    

    导入您的应用组件:

    import { Component } from '@angular/core';
    import { MenuStateService } from './menu-state.service';
    
    @Component({
      selector: 'my-app',
      template: `
      <ul id="nav-principal" *ngIf="menuStateService.isActive" class="nav nav-tabs">
        <li role="presentation" class="active"><a routerLink="/index">Index</a><li>
        <li role="presentation"><a routerLink="/socios">Socios</a><li>
      </ul>
      <router-outlet></router-outlet>
      `
    })
    
    export class AppComponent {
        constructor(public menuStateService: MenuStateService) {}
    }
    

    确保也将服务添加到您的应用程序模块providers数组中,否则您会遇到麻烦。

    然后您可以使用服务中定义的方法从任何组件启用或禁用菜单:

    import { Component } from '@angular/core';
    import { MenuStateService } from './menu-state.service';
    
    @Component({
      selector: 'socios',
      templateUrl: '../socios.html',
    })
    
    export class SociosComponent implements OnInit {
        constructor(private menuStateService: MenuStateService) {}
    
        ngOnInit(): void {
            this.menuStateService.enable();
        }
    }
    

    现在看起来可能有点矫枉过正,但随着您的应用程序的发展,您可能会发现您需要存储有关菜单的更多信息,或者可能添加额外的功能。那么你就已经有了它的位置。

    【讨论】:

    • 感谢@Brother Woodrow。我需要改进这种思维方式……干杯。
    • 它被认为是“坏的”,因为你的代码直接绑定到一个特定的环境,即浏览器,所以你不能在不同的环境中使用它。这还不错,因为它存在安全漏洞。此外,ngIf 修改 DOM 如果其表达式发生更改,它会删除或插入封闭的 DOM 对象,因此如果您只想频繁显示/隐藏某些内容,ngIf 不是最佳选择
    • 谢谢@Biu。所以,为了我的目的。在组件加载时显示的导航栏这个选项是正确的方法,不是吗?
    【解决方案2】:

    您不想用引用当前组件类的this 限定documentdocument 在全局范围内,因此请执行以下操作

    export class SociosComponent implements OnInit {
        ngOnInit(): void {
            (document.getElementById('nav-principal') as HTMLElement).style.display = "block";
        }
    }
    

    【讨论】:

    • 嗨@Dummy。很快!!有用!!谢谢! :)。干杯伙伴:)
    • 哎呀。就是这样:)
    • 大声笑...谢谢!! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多