【问题标题】:styles property is not working in the component metadata in angular 2?样式属性在角度 2 的组件元数据中不起作用?
【发布时间】: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


【解决方案1】:

代码

styles: [`
   .form-group label { 
     font-weight: bold;
     color: red; 
   }
`]

阅读styles guide

【讨论】:

  • 您的解决方案没有区别。 ` 只是多行字符串所需要的,这不是他的问题。
  • @lexith 大型内联模板和样式模糊了组件的用途和实现,降低了可读性和可维护性。
  • 是的,好吧,我也不会使用内联模板/样式,但这将如何帮助他解决问题?
  • @lexith 好的,让他更改选择器。所以它应该可以解决问题。
  • @ShubhamVerma 你最好阅读how css rules overrides
猜你喜欢
  • 2014-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-06
  • 2023-02-06
  • 2022-01-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多