如何使用 ::ng-deep 访问 CSS of Angular 子组件

How to access CSS of Angular child component with ::ng-deep

我正在尝试使用 ::ng-deep 访问和编辑子组件的 CSS class。我尝试了下面提供的代码的不同版本,但无法访问 CSS。 HTML组件的结构如下:

这就是我尝试从父组件访问 CSS 并更改 class:

grid-template-columns 属性 的方式
::ng-deep{
  app-operator-filter{
    .header-logos-card{
      grid-template-columns: repeat(4,1fr);
    }
  }
}

实现此目的的正确语法是什么?我也对访问子组件的其他建议持开放态度,因为我读到 ::ng-deep 不可靠并且可能很快就会被弃用?

它应该有效

::ng-deep .header-logos-card {
  grid-template-columns: repeat(4,1fr);
}

::ng-deep 将来会被弃用是的。另一种方法是从 child.

导入 CSS/SCSS 文件

parent-component.css

.header-logos-card {
  grid-template-columns: repeat(4, 1fr);
}

child-component.css

@import './path/to/parent-component.css';

更多关于 Angular css 导入 here

这个问题的解决方法是这样的:

:host ::ng-deep app-operator-filter{
  .header-logos-card {
    grid-template-columns: repeat(4,1fr) !important;
  }
}

!important 是一个至关重要的补充,因为没有它,更改将被覆盖。

对任何 CSS 规则使用 ::ng-deep pseudo-class 将完全破坏该规则的 view-encapsulation 并成为全球风格。因此,按照 Angular 官方 Doc 的建议,尝试将其与 :host 一起使用。

Applying the ::ng-deep pseudo-class to any CSS rule completely disables view-encapsulation for that rule. Any style with ::ng-deep applied becomes a global style. In order to scope the specified style to the current component and all its descendants, be sure to include the :host selector before ::ng-deep. If the ::ng-deep combinator is used without the :host pseudo-class selector, the style can bleed into other components.

所以,尝试这样的事情:

:host ::ng-deep app-operator-filter {
  .header-logos-card {
    grid-template-columns: repeat(4,1fr);
  }
}

::ng-deep 背后的问题是它使它成为一个全局选择器,以防止您需要始终在它之前使用 :host。

根据文档:

Applying the ::ng-deep pseudo-class to any CSS rule completely disables view-encapsulation for that rule. Any style with ::ng-deep applied becomes a global style. In order to scope the specified style to the current component and all its descendants, be sure to include the :host selector before ::ng-deep. If the ::ng-deep combinator is used without the :host pseudo-class selector, the style can bleed into other components.

所以正确答案是:

:host {
  ::ng-deep {
    .header-logos-card {
      grid-template-columns: repeat(4,1fr);
    }
  }
}

或者从 child:

导入样式
@import './path/to/parent-component.css';

而不是像这样使用它:

:host {    
  .header-logos-card {
    grid-template-columns: repeat(4, 1fr);
  }
}

Ng deep 已弃用,请勿使用。而是同时使用根级别和组件级别 sass。它工作起来容易得多。如果你有兴趣,我有这方面的文章。

  1. 在 app-parent.component.ts 文件中将 viewEncapsolution 设置为 none。

    import { Component,ViewEncapsulation} from '@angular/core';
    
    @Component({
       selector: 'app-parent-selector',
       templateUrl: './app-parent.component.html',
       styleUrls: ['./app-parent.component.css'],
       encapsulation:ViewEncapsulation.None
    })
    
  2. 在 app-parent.component.css 文件中用子选择器包裹子 css class。

    app-operator-filter {
      .header-logos-card {
        grid-template-columns: repeat(4,1fr);
      }
    }