如何通过选择器将 CSS 应用于组件的元素 - Angular7/8

How to apply CSS to the elements of a component through its selector - Angular7/8

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

您在 SCSS 中应用了错误的语法,当您想要 select 一个同时具有 select 或两个元素的元素时,使用了连字符 (&),当您这样做时:

app-input{
    & .an-input{
        width: 100%;
    }
}

您正在 selecting 所有 app-input 类型的元素,这些元素还具有 .an-input class,而不是具有 .an-input class.

app-input 子元素

所以,删除 & :

app-input{
    .an-input{
        width: 100%;
        input{
            border-color: red;
        }
    }
}

更多信息:https://css-tricks.com/the-sass-ampersand/

angular 方法是将样式作为输入 属性 传递给您的自定义输入

@Input() styles: any;

并将其绑定到 ngStyle 属性 as

[styles]="styles"

演示地址:https://stackblitz.com/edit/angular-ngstyle-as-input-property

PS:作为用户之一提到使用::ng-deep,不建议这样做,很快就会被删除。更多信息 HERE