AngularJs给自定义组件添加样式不起作用怎么办?

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jaune161/article/details/87433506

首先看一个自定义组件

panel.component.html

<div class="app-panel" [style]="style">
    <ng-content></ng-content>
</div>

panel.component.ts

import { Component, Input, OnInit } from '@angular/core';

@Component({
    selector: 'app-panel',
    templateUrl: './panel.component.html',
    styleUrls: ['./panel.component.css']
})
export class PanelComponent implements OnInit {

    @Input() style: any;

    constructor() {
    }

    ngOnInit() {
    }

}

panel.component.css

.app-panel {
    background: #fff;
    padding: 24px;
}

当我们使用时可能需要根据不同的场景来添加一些自定义的样式,比如这样

<app-panel style="margin-top: 20px;">
  <button></button>
</app-panel>

这时候就会发现样式设置不管用,这是为什么呢?这是因为app-panel在页面上会以一个非标准的HTML标签存在。
image.png

image.png

而这个标签并没有占用页面上的任何位置,所以无论我们怎么设置样式,都是不会起作用的。
这时候只需要修改panel.component.css,增加下面的样式。

:host {
  display: block;
}

:host 代表的就是组件自身,也就是app-panel,设置这个样式的目的是为了让组件以块的形式存在。这样我们就可以直接在组件上定义样式了。
image.png

猜你喜欢

转载自blog.csdn.net/jaune161/article/details/87433506