【发布时间】:2019-08-02 23:32:58
【问题描述】:
我正在开发一个 Angular 7/8 应用程序。我制作了一个自定义的input 组件,它的选择器称为<app-input></app-input>。这个input 有一些特定的样式,我可能想在其他地方更改,例如,默认情况下border-color 是blue,而在另一个组件中,我想将其样式更改为red。问题是我无法访问<app-input></app-input> 中的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;
}
}
}
【问题讨论】:
-
我找到了答案here,这可能对你有帮助。
-
您可以使用 ::ng-deep 访问后代,但很快它将被删除。但是,您可以在子样式中声明
host-context()以在父是主机上下文中的内容时应用一些样式。 stackoverflow.com/questions/48071237/… -
@Sergey 见angular.io/guide/component-styles。 ::ng-deep 已被贬低
-
@Saksham 已弃用但未删除,因此仍然可以使用。请注意,我在评论中也注意到了这一点,并提出了替代方案。
-
@Sergey 我用过,但没那么深。