【发布时间】:2020-08-31 00:20:34
【问题描述】:
目标:让 CSS 只影响其所在的组件,而不影响其他组件。我只想影响我的下拉菜单,而不是其他文本输入字段:
背景/问题:我理解为什么它会影响同一页面上的多个项目(mat-form-field 的)。但不明白为什么它会影响其他页面。我调查了它,但仍然不确定。
我尝试了什么: 例如,我原来有:
::ng-deep .mat-form-field-appearance-outline .mat-form-field-flex {
height: 40px !important
}
::ng-deep .mat-form-field-infix {
padding-top: 1px !important;
padding-bottom: 2px !important;
}
但它会影响页面上所有表单域的间距,所以我将其编辑为:
::ng-deep .mat-form-field-appearance-outline .mat-form-field-flex {
height: 40px !important
}
::ng-deep .mat-form-field-appearance-outline .mat-form-field-infix {
padding-top: 1px !important;
padding-bottom: 2px !important;
}
其他未更改的 CSS:
.title-container {
position: relative;
margin-top: 8px;
}
.language-field {
position: absolute;
right: 0;
top: 0;
margin-top: -16px;
width: 115px;
height: 20px !important;
}
这解决了这个问题,但我仍然奇怪的是,更改 login.component.css 上的某些内容会影响站点中的所有其他页面,例如 profile.component.css
这里是 login.component 的关联 HTML:
<div class="title-container">
<mat-card-title class="text-center">
Please Sign In
</mat-card-title>
<form [formGroup]="_siteForm">
<mat-form-field class="language-field" appearance="outline">
<mat-select (selectionChange)="changeSite($event)" [value]="languages[i].value">
<mat-option *ngFor="let language of languages" [value]="language.value">
{{language.viewValue}}
</mat-option>
</mat-select>
</mat-form-field>
</form>
</div>
当我对此进行研究时: 我发现一些 SO 文章(例如 Angular 2+ : Component style keeps affecting other components)提到使用封装:ViewEncapsulation 但是,在浏览该站点时,我没有看到它在任何地方使用,但是在不同的组件上都有 css,它们都提到了 mat-form-field 但具有不同的值。这似乎表明不需要封装。 在常规的 HTML 中,我没有遇到过这些问题,但对它在 Angular 中的工作方式感到困惑。这是否与 Angular 成为 SPA 有关?
【问题讨论】:
-
请注意,
::ng-deep是 deprecated,但没有关于何时将其删除的时间表。