在Angular 4中如何使用::ng-deep,在哪里使用?
实际上,我想从父组件中覆盖子组件的一些CSS属性。此外,IE11支持它吗?
在Angular 4中如何使用::ng-deep,在哪里使用?
实际上,我想从父组件中覆盖子组件的一些CSS属性。此外,IE11支持它吗?
当前回答
我浏览了所有这些答案,发现没有人提到子组件可以从父组件传递样式CSS。
在组件的文件中,你可以这样做:
@Input() styles: any = {};
在组件html文件中,你使用这个:
[ngStyle]="styles"
在parent中,你可以这样使用:
<yourComponent [styles]="{backgroundColor: 'blue', 'font-size': '16px'}">
请在这里查看更多细节:将样式传递给组件的最佳方式
通过这种方式,我们没有破坏封装,这是最重要的面向对象原则之一
其他回答
更新一下:
你应该使用::ng-deep而不是/deep/,这似乎是不推荐的。
每个文档:
暗影穿透的后代组合子已弃用,支持是 从主流浏览器和工具中删除。因此,我们打算放弃 Angular中的支持(支持/deep/、>>>和::ng-deep中的所有3个)。直到 那么::ng-deep应该优先用于更广泛的兼容性 的工具。
你可以在这里找到它
使用
::ng-deep, >>> and /deep/ disable view encapsulation for specific CSS rules, in other words, it gives you access to DOM elements, which are not in your component's HTML. For example, if you're using Angular Material (or any other third-party library like this), some generated elements are outside of your component's area (such as dialog) and you can't access those elements directly or using a regular CSS way. If you want to change the styles of those elements, you can use one of those three things, for example:
::ng-deep .mat-dialog {
/* styles here */
}
目前,Angular团队建议只使用EMULATED视图封装来进行“深度”操作。
弃用
“deep”操作实际上也被弃用了,但它现在仍然有效,因为Angular支持预处理(今天不要急于拒绝::ng-deep,先看看弃用实践)。
无论如何,在采用这种方法之前,我建议您看看禁用视图封装方法(这也不是理想的方法,它允许您的样式泄漏到其他组件中),但在某些情况下,这是一种更好的方法。如果您决定禁用视图封装,强烈建议使用特定的类来避免CSS规则的交叉,最后,避免样式表中的混乱。在组件的.ts文件中禁用它真的很容易:
@Component({
selector: '',
template: '',
styles: [''],
encapsulation: ViewEncapsulation.None // Use to disable CSS Encapsulation for this component
})
您可以在本文中找到关于视图封装的更多信息。
我浏览了所有这些答案,发现没有人提到子组件可以从父组件传递样式CSS。
在组件的文件中,你可以这样做:
@Input() styles: any = {};
在组件html文件中,你使用这个:
[ngStyle]="styles"
在parent中,你可以这样使用:
<yourComponent [styles]="{backgroundColor: 'blue', 'font-size': '16px'}">
请在这里查看更多细节:将样式传递给组件的最佳方式
通过这种方式,我们没有破坏封装,这是最重要的面向对象原则之一
请谨慎使用::ng-deep。我在我的应用程序中使用它来设置材质设计工具栏的颜色,在我的应用程序中,却发现当应用程序在测试工具栏的颜色时,它们会相互踩在一起。这是一个不渗透到其他组件的工作代码解决方案。
<mat-toolbar #subbar>
...
</mat-toolbar>
export class BypartSubBarComponent implements AfterViewInit {
@ViewChild('subbar', { static: false }) subbar: MatToolbar;
constructor(
private renderer: Renderer2) { }
ngAfterViewInit() {
this.renderer.setStyle(
this.subbar._elementRef.nativeElement, 'backgroundColor', 'red');
}
}
通过要求父类是一个封装的css类,我要强调将::ng-deep限制为组件的子类的重要性。
要做到这一点,重要的是在父类之后使用::ng-deep,而不是在父类之前使用,否则它将在加载组件时应用于所有同名的类。
在::ng-deep之前使用:host关键字将自动处理此问题:
:host ::ng-deep .mat-checkbox-layout
或者你也可以通过在::ng-deep关键字之前添加一个组件作用域的CSS类来实现相同的行为:
.my-component ::ng-deep .mat-checkbox-layout {
background-color: aqua;
}
组件模板:
<h1 class="my-component">
<mat-checkbox ....></mat-checkbox>
</h1>
生成的(Angular生成的)css将包含唯一生成的名称,并且只应用于它自己的组件实例:
.my-component[_ngcontent-c1] .mat-checkbox-layout {
background-color: aqua;
}