【问题标题】:How to manipulate a <DIV> style in Angular 8如何在 Angular 8 中操作 <DIV> 样式
【发布时间】:2020-03-19 16:29:24
【问题描述】:

想要操纵样式的显示。这是模板:

<div style="display: none" #myDiv />

认为有两种方法可以做到:

  1. 直接

    if (1===1) this.myDiv.style.display = "block";

  2. 通过@ViewChild

    @ViewChild('myDiv', { static: false}) myDiv if (1===1) this.myDiv.style.display = "block";

没有工作。

【问题讨论】:

标签: css angular typescript styles angular8


【解决方案1】:

您可以使用ElementRef,如下所示。

HTML

<div class="my-div" style="display: none" />

TS

export class MyComponent implements AfterViewInit  {

  myDiv;

  constructor(private elementRef:ElementRef) {}

  ngAfterViewInit() {

    this.myDiv = this.elementRef.nativeElement.querySelector('.my-div');
  }
}

然后您可以使用myDiv 变量更改样式,如下所示。

this.myDiv.style.display = 'block';

StackBlitz Demo.

【讨论】:

  • 这不是针对一个指令/属性的大量输入吗?或者它可能比 ngStyle 有一些优势?
  • 这是您以编程方式更改DOM 样式的方式,或者您可以使用ngClass 并根据一些布尔变量更改类。
  • ngStyle 呢?
  • ngStyle 也很好。但它是有限的。如果您使用ngClass,您可以使用任意数量的类,而boolean 变量很少
【解决方案2】:

使用ngStyle:

<div [ngStyle]="{'display': flag ? 'block' : 'none'}">
    ...
</div>

其中flag 可以根据您在相应 .ts 文件中的逻辑对应于任何布尔变量。

【讨论】:

    【解决方案3】:

    您也可以使用Renderer2设置样式,setStyle的原型如下:

    setStyle(el: any, style: string, value: any, flags?: RendererStyleFlags2): void

    参数:

    el: any,     The element for whcih you set the style.
    
    style:  string,  The name of the style.
    
    value:  any,      The new value for style.
    
    flags   RendererStyleFlags2,  Flags for style variations. No flags are set by default.
    

    所以你必须避免使用ElementRef,因为直接访问dom不利于安全,不安全,你可以使用Renderer2来设置Style

    演示示例:

    https://stackblitz.com/edit/renderer2-example-2-oryw2m?file=src/app/app.component.ts

    代码示例:

    import { Component, Renderer2, AfterViewInit, ViewChild, ElementRef } from '@angular/core';
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: [ './app.component.css' ]
    })
    export class AppComponent implements AfterViewInit {
      @ViewChild('test') test: ElementRef;
    
      constructor(private renderer: Renderer2) {}
    
      ngAfterViewInit() {
        this.renderer.setStyle(this.test.nativeElement, 'backgroundColor', 'red');
        this.renderer.setStyle(this.test.nativeElement, 'color', 'white');
      }
    }
    

    【讨论】:

    • 感谢您提供的详细信息,正如您在另一个post 中回答的那样,[ngStyle] 实际上是使用Renderer,我会选择更简单的ngStyle
    猜你喜欢
    • 1970-01-01
    • 2020-05-30
    • 2021-05-29
    • 2013-10-15
    • 2014-10-28
    • 1970-01-01
    • 1970-01-01
    • 2020-07-31
    • 2019-12-14
    相关资源
    最近更新 更多