首页 > 解决方案 > 如何通过其选择器将 CSS 应用于组件的元素 - Angular7/8

问题描述

我正在开发一个 Angular 7/8 应用程序。我制作了一个自定义input组件,它的选择器被称为<app-input></app-input>. 这input有一些我可能想在其他地方更改的特定样式,例如,默认情况下border-coloris 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;
        }
    }
}

标签: angularangular7angular8

解决方案


您在 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/


推荐阅读