【问题标题】:How to apply CSS to the elements of a component through its selector - Angular7/8如何通过其选择器将 CSS 应用于组件的元素 - Angular7/8
【发布时间】:2019-08-02 23:32:58
【问题描述】:

我正在开发一个 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;
        }
    }
}

【问题讨论】:

  • 我找到了答案here,这可能对你有帮助。
  • 您可以使用 ::ng-deep 访问后代,但很快它将被删除。但是,您可以在子样式中声明 host-context() 以在父是主机上下文中的内容时应用一些样式。 stackoverflow.com/questions/48071237/…
  • @Sergey 见angular.io/guide/component-styles。 ::ng-deep 已被贬低
  • @Saksham 已弃用但未删除,因此仍然可以使用。请注意,我在评论中也注意到了这一点,并提出了替代方案。
  • @Sergey 我用过,但没那么深。

标签: angular angular7 angular8


【解决方案1】:

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

@Input() styles: any;

并将其绑定到ngStyle 属性

[styles]="styles"

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

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

【讨论】:

  • 我认为我应该使用这种方法,它更方便但令人头疼,尽管我需要为每个元素传递不同的样式。
  • 虽然这行得通,但我认为这不是最好的方法,因为每次要将样式应用于元素时都必须使用此逻辑。
【解决方案2】:

您在 SCSS 中应用了错误的语法,当您想要选择具有两个选择器的元素时,使用符号 (&),当您这样做时:

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

您正在选择所有app-input 类型的元素也有.an-input 类,而不是具有.an-input 类的app-input 子元素。

所以,删除 &amp;

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

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

【讨论】:

  • 样式仍然没有被应用!
猜你喜欢
  • 2020-11-19
  • 1970-01-01
  • 2021-04-15
  • 1970-01-01
  • 2019-07-20
  • 1970-01-01
  • 1970-01-01
  • 2019-04-30
  • 2015-10-15
相关资源
最近更新 更多