如何防止 Angular 组件样式覆盖转移到其他组件? [英] How do I prevent Angular component styling override from carrying over to other components?

查看:36
本文介绍了如何防止 Angular 组件样式覆盖转移到其他组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个 Angular 组件可以来回路由.他们都有mat-form-field.在一个组件中,我像这样覆盖了下划线组件的样式:

I have a couple Angular components that route back and forth to one another. They both have mat-form-field's. In one component, I am overriding the styling of the underline component like so:

::ng-deep .mat-input-underline {
  display: none;
}

当我点击链接返回到另一个组件时,上面定义的样式继续存在,下划线组件消失了.我尝试添加如下样式:

When I click on the link to go back to the other component, the styling as defined as above carries over and the underline components are gone. I tried to add styling like:

::ng-deep .mat-input-underline {
  display: revert;
  //or
  display: unset;
  //or
  display: initial;
}

但它们都不起作用.如何仅覆盖一个组件而不覆盖其他组件的 Material Design 样式?

But none of them work. How can I override the material design styling on just one component but not the others?

推荐答案

您的问题是由 ::ng-deep 引起的,它会在组件加载后将样式应用于页面中的所有 .mat-input.underline 元素和风格注入.

Your issue is caused by ::ng-deep, which will apply style to all .mat-input.underline elements in the page once the component has been loaded and style injected.

如果你真的想保留 ::ng-deep 组合器,你可以添加 :host 选择器到你的规则的前缀,这将针对宿主元素并且不会将 css 泄漏到其他组件(除了子组件)

If you really want to keep the ::ng-deep combinator, you can add the :host selector to prefix your rule, which will target the host element and not leak the css to other components (apart from child components)

:host ::ng-deep .mat-input-underline
{
  display: none;
}

https://angular.io/guide/component-styles#host

这篇关于如何防止 Angular 组件样式覆盖转移到其他组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆