【发布时间】:2017-01-31 16:43:35
【问题描述】:
我是 Angular 2 的新手,我正在创建一个演示应用程序,并希望在 component 元数据中为 contact.component.html 中的所有标签设置 styles 属性。
我添加了styles: ['label { font-weight: bold;color:red }'] 来解决我的问题,但我的视图上没有显示 CSS 效果。
我知道我可以使用styleUrls: [ '../css/contact.component.css' ],但不想这样做。我想学习在组件元数据中设置样式属性。
请说明为什么这种效果没有显示在视图上?
@Component({
moduleId: module.id,
selector: 'app-contact',
templateUrl: '../views/contact.component.html',
styles: ['label { font-weight: bold;color:red }']
})
contact.component.html:
<h2 highlight>Contact of {{userName}}</h2>
<h2 myHighlight>This is custom my directive</h2>
<div *ngIf="msg" class="msg">{{msg}}</div>
<form *ngIf="contacts" (ngSubmit)="onSubmit()" #contactForm="ngForm">
<h3 >{{ contact.name | awesome }}</h3>
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" required [(ngModel)]="contact.name" name="name" #name="ngModel" >
<div [hidden]="name.valid" class="alert alert-danger">Name is required </div>
</div>
<div class="form-group">
<label for="EmailId">Email</label>
<input type="email" class="form-control" required [(ngModel)]="contact.email" name="email" #email="ngModel">
<div [hidden]="email.valid" class="alert alert-danger">email is required </div>
</div>
<button type="submit" class="btn btn-default" [disabled]="!contactForm.form.valid">Save</button>
</form>
查看快照:
【问题讨论】:
-
您确定没有全局样式可以推翻您的本地样式吗?
-
装饰器中定义的样式应该优先于全局css,所以如果他在某个地方没有
label { color: grey!important; },那就不是这样了,或者? -
@lexith 没错,但对我来说代码看起来不错,因此问题必须出在其他地方。我不认为
important是必要的。label[for][for] { }也可能有效。组件样式具有更高的特异性,但您可以在没有!important的情况下增加全局样式的特异性。
标签: html css angular typescript