如何构建自定义 angular 组件,其宽度可在 CSS 中设置?

How can i build a custom angular component with the width settable in CSS?

这个 site 声明,我可以像这样用 CSS 改变侧边导航的宽度:

md-sidenav {
   width: 200px;
}

这引起了我的以下问题:我可以将标准 CSS 属性(如 widthposition 等)应用于自定义组件,而无需在我的自定义组件中定义它们吗?零件?

示例:

my-component {
    width: 500px;
}

我试过了,还是不行。所以我想,答案是否定的,对吗?

为了了解他们如何将 width 设置为 CSS,我通读了 github 上的资料。但我想不通他们是怎么做到的。该组件没有 width 属性。那么,他们是如何让 width 可以通过 CSS 访问的?


编辑:

为了澄清这个问题,我会给你下面的例子:

我编写了以下组件:

test.component.html:

<p>test works!</p>

test.component.css:

p {
   border: 2px solid red;
}

test.component.ts:

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

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

  constructor() { }

  ngOnInit() { }

}

这是我的应用根目录,由 angular:

引导

app.component.html:

<app-test>

</app-test>

app.component.css

app-test {
  height: 100px;
  width: 200px;
}

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Test App';
  constructor() { }

}

_app.component.css_ 显示了我想做的事情。我想用 CSS 设置 _app-test_ 组件的大小。我看到它与 angular material 的 _side-nav_ 组件一起工作,我想了解他们如何启用 _side-nav_ 从父组件 CSS 文件中获取其宽度。

OP 编辑​​后更新:

将您的 app.component.css 更改为:

:host {
  display:block; 
  height: 100px;
  width: 200px;
}

这将在 <app-test> 选择器上应用样式。这是 plunker demo.


原始答案:

您可以通过在组件中设置encapsulation: ViewEncapsulation.None来覆盖Material 2个组件的默认样式。

然后您必须在 component.css 文件中定义样式。

.mat-sidenav {
    width: 250px;
}

查看这个 plunker demo 用户定义的宽度。


OP评论后更新:

假设你有一个组件文件,my.component.ts,它的样式在my.component.css,你可以在css文件中定义组件的样式,然后应用到组件上选择器使用 :host.

my.component.ts :

@Component({
    selector: 'my-comp', 
    templateUrl: 'my.component.html',
    styleUrls: ['my.component.css']
})
export class MyComponent{
}

my.component.css :

:host {
    width: 500px;
    background-color: red;
}

my.component.html:

<h2>Some Heading in the Template </h2>

我的问题在 Will howel 的评论下得到了回答。这篇post应该把我从其他网友的评论中学到的东西总结一下,让有类似问题的人可以借鉴一下。

每个组件的模板都包裹在一个宿主元素中。在 sidenav 示例中,此元素是 md-sidenav 标记。宿主元素是常规 dom 元素,因此您可以向该元素添加标准 css 规则。这意味着您可以立即将 css 规则(例如 width)应用于每个自定义 angular 组件。但是你必须考虑到你需要将宿主元素的 display 属性 设置为 block。如果你不这样做,宽度规则对元素没有影响。 为了在 md-sidenav 组件的情况下实现这一点,他们在 组件中应用了 class mat-drawer -decorator 到元素。

摘自sidenav.ts:

    host: {
    'class': 'mat-drawer mat-sidenav',
    ...
  },

然后他们在样式表中设置规则。 drawer.scss的摘录:

 .mat-drawer {
     @include mat-drawer-stacking-context();

     display: block;
}