【问题标题】:ngClass doesn't apply style from .scss using bindingngClass 不使用绑定从 .scss 应用样式
【发布时间】:2019-03-01 10:59:02
【问题描述】:

我的问题是 sm-input-text.component,它没有使用绑定 page-input-text.component.scss 应用样式strong>[cssClass] 输入。 但价值就在那里。

我有两个组件:

- sm-input-text.component.html
- sm-input-text.component.ts
- sm-input-text.component.scss
- page-input-text.component.html
- page-input-text.component.ts
- page-input-text.component.scss

我的代码如下:

sm-input-text.component.html:
i bind the [ngClass] <-> cssClass

    <mat-form-field [formGroup]="formGroup">
      <input
        matInput
        type="text"
        [placeholder]="placeholder"
        [formControlName]="fControlName"
        (input)="onInput($event)"

        [ngClass]="cssClass"
      >
    </mat-form-field>

page-input-text.component.html: i give value to the [cssClass]

    <form [formGroup]="formGroupOnlyOne">
        <sm-input-text
          #input1
          [formGroup]="formGroupOnlyOne"
          fControlName="input1"
          placeholder="InputText"

          [cssClass]="'no-selectable'"
        ></sm-input-text>
    </form>

page-input-text.component.scss:

    .no-selectable {
        cursor: auto;
        background: red;
    }

不适用。但是,如果我将“不可选择”样式添加到 sm-input-text.component.scss 中,则会应用并显示它! 我只想在 page-input-text.component 的 ma​​tInput 上添加样式。 我在这里错过了什么?

【问题讨论】:

    标签: angular input angular-material


    【解决方案1】:

    因为 Angular 有 View Encapsulation,所以不能将 child 的 CSS 样式类添加到 parent,除非它的两个封装都设置为 ViewEncapsulation.None。您应该在sm-input-text.component.scss 中添加此类。或者你可以在你的styles.scss中全局添加它

    styles.scss

    .no-selectable {
        cursor: auto;
        background: red;
    }
    

    每当 Angular 渲染一个组件时,它会使用 CSS 中生成的属性选择器更改你的 CSS 以使其与该组件单独匹配

    例如

    .no-selectable[ng-content23] {
        cursor: auto;
        background: red;
    }
    

    如果你想解决你的问题,你可以将你的组件封装设置为ViewEncapsulation.None

    @Component({
      selector: 'my-app',
      template: `
        <h1>Hello World!</h1>
        <span class="red">Shadow DOM Rocks!</span>
      `,
      styles: [`
        :host {
          display: block;
          border: 1px solid black;
        }
        h1 {
          color: blue;
        }
        .red {
          background-color: red;
        }
    
      `],
      encapsulation: ViewEncapsulation.None
    })
    class MyApp {
    }
    

    您应该将ViewEncapsulation.None 设置为 sm-input-text.component.ts, page-input-text.component.ts

    【讨论】:

    • 很好的解释,谢谢!我尝试了封装和全局样式,并且确实在我的浏览器中显示了样式,但仍然无法正常工作。我认为有一些mat-form-field问题。例如:如果我将 [cssClass] 输入提供给 mat-form-field 则可以,但如果我将其提供给 matInput 则它不起作用,是否会覆盖它?
    • 请检查 matinput api in angular material 肯定有办法添加类
    • 不要使用[ngClass]="cssClass",而是使用[class]="cssClass"
    • 我检查了文档,是的,您可以在 mat 表单字段中添加 css。如果您将其添加到 mat 输入,它们将使用其材质样式覆盖它。
    猜你喜欢
    • 2018-10-27
    • 2021-03-21
    • 1970-01-01
    • 1970-01-01
    • 2018-12-04
    • 2018-02-28
    • 2021-09-22
    • 2021-07-10
    • 1970-01-01
    相关资源
    最近更新 更多