首页 > 解决方案 > 如何在 Angular 8 中覆盖自定义组件 css

问题描述

我试图覆盖自定义组件选择器的 css,但它不起作用。我试过:ng-deep没有成功。我该如何找到解决方案?

app.component.html:

<mycustommcomp></mycustommcomp>

app.component.css:

::ng-deep mycustommcomp{ 
margin:2px;
overflow:unset !important; 
}

mycustomcomp.component.css:

mycustommcomp{ 
margin:8px;
overflow:hidden !important; 
}

演示:https ://stackblitz.com/edit/angular-vsdzqs?file=src/app/app.component.css

标签: csstypescriptangular7angular8

解决方案


您不能这样做,因为样式不能应用于组件标签。使其工作的一种方法是使用容器(例如 div)将内容包装在 mycustommcomp 中。

mycustommcomp.component.html:

<div class="container">
   <!--Content here-->
</div>

app.component.css:

::ng-deep .container{ 
   margin:2px;
   overflow:unset !important; 
}

mycustomcomp.component.css:

.container{ 
   margin:8px;
   overflow:hidden !important; 
}

尽管如此,请避免这样做,因为 ::ng-deep 已弃用


推荐阅读