我在我的角度项目中对组件的样式有疑问。我基本上无法正常工作。为了解释我的问题,我使用Angular CLI(CLI 6.0.8,angular 6.1.0)创建了一个新项目。马上,我创建了一个新的测试组件,在其中声明以下内容:
- - - - - - - - - - - - -
COMPONENT TEMPLATE FILE:
- - - - - - - - - - - - -
<div>with div</div>
without div
- - - - - - - - - - - - -
COMPONENT STYLE FILE:
- - - - - - - - - - - - -
:host
{
background-color: blue;
}
(无需更改打字稿声明文件)
我将此组件包括在应用程序模板中,并在app.css文件中为其声明了一些样式:
- - - - - - - - - - - - -
APP TEMPLATE FILE:
- - - - - - - - - - - - -
<app-test class='test'></app-test>
- - - - - - - - - - - - -
APP STYLE FILE:
- - - - - - - - - - - - -
.test
{
background-color: red;
width: 350px;
}
这是我得到的结果:
IMAGE:元素的宽度未更新,并且未显示元素大小,如使用chrome时通常那样
如图中所示,无论是在父作用域还是在组件作用域(使用:host)中定义的样式,都无法正确应用。样式已更新,但未显示。当我在浏览器中将“ app-test”标签更改为“ div”标签时(使用调试工具>编辑为HTML),它会正确显示:
我认为这与角度显示组件的方式有关,因为将标签更改为DIV即可。但是我不明白这个问题是从哪里来的。此问题出现在使用CLI新建的项目中,未在项目配置中进行任何配置...
谁能帮我?
关于您在测试组件中所面临的宽度问题,假设您希望整个元素的宽度为350px,则应定义其display属性以进行阻止:
:host {
background: blue;
display: block;
}
自定义元素没有默认的显示属性,您的浏览器无法猜测您的意思是什么。
关于.test
在您的组件上应用样式,app-component
样式会使用_nghost-c0
和_ng-content-c0
属性进行封装,因此不会应用于test.component
。如果要.test
在其他组件上应用,则可以在全局应用的全局文件上编写CSS RULEstyles.css
:
//styles.css
.test {
background-color: red;
width: 350px;
}
或像这样使用装饰器viewEncapsulation
上的属性@component
:
//app.component.ts
import { Component, ViewEncapsulation } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
encapsulation: ViewEncapsulation.None
})
然后可以将CSS RULE保留在app.component
文件上
//app.component.css
.test {
background-color: red;
width: 350px;
}
但现在该文件中的样式尚未封装,并且会渗透到其他组件中。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句