首页 > 解决方案 > 为什么这个组件没有应用 css 规则?

问题描述

我有一个名为 的组件app-list-container,其结构如下:

HTML

<ul [attr.styleName]="styleName" [style.flexGrow]="flexGrow">
    <!-- ITEM <li> -->
    <ng-content></ng-content>
</ul>

SCSS

@import 'placeholders/scrollbar';

ul {
    &[styleName='CHAT_MESSAGE'],
    &[styleName='CHAT_LAST_MESSAGE'] {
        @extend %scrollbar-y;
    }
}

有了这个,我<li>在这个组件中生成了项目()......现在我不明白为什么它不应用这个css规则。

该规则仅在我将其插入他的父亲 ( app-list-container) 时适用,对我来说,通过父亲也插入样式是没有意义的。

请注意,在下图中,css 正在应用于 html 元素,但如果应用于 html 元素,则它<ul> 不起作用,但如果应用于父元素( <app-list-containr>),则它可以工作:

在此处输入图像描述

该怎么办?(注意:我喜欢做并且知道正确的模式)。

标签: angularangular-components

解决方案


对于那些想知道的人,我是这样做的:

TS:

export class ListContainerComponent implements OnInit {
    @HostBinding('attr.styleName') hostStyleName: IListStyleName;
    @Input() styleName: IListStyleName;
    @Input() flexGrow = ICssFlexGrow.INITIAL;

    constructor() {}

    ngOnInit(): void {
        this.checkInput();
        this.setHostStyleName(this.styleName);
    }

    protected checkInput(): void {
        if (!IListStyleName[this.styleName.toUpperCase()]) {
            throw new Error(`The inserted style: "${this.styleName}" does not exist in this component!`);
        }

        if (!ICssFlexGrow[this.flexGrow.toUpperCase()]) {
            throw new Error(`The inserted flex-grown: "${this.flexGrow}" does not exist in this component!`);
        }
    }

    protected setHostStyleName(styleName: IListStyleName): void {
        this.hostStyleName = styleName;
    }
}

SCSS:

:host {
    &[styleName='CHAT_MESSAGE'],
    &[styleName='CHAT_LAST_MESSAGE'] {
        @extend %scrollbar-y;
    }
}

推荐阅读