angular - 如何通过其选择器将 CSS 应用于组件的元素 - Angular7/8
问题描述
我正在开发一个 Angular 7/8 应用程序。我制作了一个自定义input
组件,它的选择器被称为<app-input></app-input>
. 这input
有一些我可能想在其他地方更改的特定样式,例如,默认情况下border-color
is blue
,而在另一个组件中,我想将其样式更改为red
. 问题是我无法input
访问<app-input></app-input>
.
在父组件中,我将样式应用为:
我正在使用 SCSS
//Styles from parent component
app-input{
& .an-input{
width: 100%;
& input{
border-color: red;
}
}
}
输入<app-input></app-input>
组件代码
//Template
<div class="an-input">
<input
[type]="type"
[id]="id"
[name]="name"
(focus)="inputFocus($event)"
(blur)="inputBlur($event)"
(input)="userTyping($event)"
class="an-input-el"
/>
<label [for]="id">
{{label}}
</label>
</div>
//Styles
.an-input{
display: inline-block;
position: relative;
width: 100%;
margin-bottom: 30px;
& input, & textarea{
padding: 15px;
color: $an-color;
border: none;
outline: none;
border: 2px solid $font-darker;
border-radius: 2px;
width: 100%;
&.input-fly{
border-color: $an-color;
}
&.input-fly-error{
border-color: maroon;
}
}
& label{
position: absolute;
left: 0;
padding: 0 10px;
font-size: 13px;
transition: .1s;
cursor: text;
color: $font-darker;
font-size: 11px;
&.label-fly{
padding: 0px;
color: $an-color;
}
}
}
解决方案
您在 SCSS 中应用了错误的语法,当您想要选择具有两个选择器的元素时,使用符号 (&),当您执行以下操作时:
app-input{
& .an-input{
width: 100%;
}
}
you're selecting all the elements of type app-input
that also have the .an-input
class, not the app-input
child elements that have the .an-input
class.
So, remove the &
:
app-input{
.an-input{
width: 100%;
input{
border-color: red;
}
}
}
More info: https://css-tricks.com/the-sass-ampersand/
推荐阅读
- google-chrome-extension - 如何使用 DevTools 或其他调试器调试 chrome 扩展?
- python-3.x - Docker 和 Plotly
- mongodb - MongoDB $group 操作 - 内存使用优化
- angular - 更改 firebase-messaging-sw.js 位置
- python - 如何将我的 django 路径设置为 http://127.0.0.1:8000/myproject/admin
- erlang - mnesia:read 在 mnesia 中使用表碎片时返回空,但有记录
- scala - 在播放控制器中注入模拟服务对象的依赖项,同时对其进行单元测试
- artifactory - JFrog Artifactory 中的本地仓库、远程仓库和虚拟仓库有什么区别
- javascript - 如何在 Javascript 中将“ArrayBuffer”转换为“SharedArrayBuffer”?
- python - 如何复制具有特定扩展名的文件夹目录中的文件并将其保存到新文件夹而不覆盖复制的文件?