如何使用ngStyle覆盖子元素样式

时间:2018-03-29 19:29:57

标签: css angular

我需要为整个div设置样式,但它对子组件不起作用:

<div class=“myClass” [ngStyle]="{'cursor': 'not-allowed'}">
        <button class=“myButton”>
                OK
         </button>
 </div>

我该怎么做?对于这种情况也一样:

<div class=“myClass” [ngStyle]="{'cursor': 'not-allowed'}">
        <button class=“myButton” [ngStyle]="{'cursor': 'default'}">
                OK
         </button>
 </div>

1 个答案:

答案 0 :(得分:0)

修改

在您的第一个示例中,问题只是浏览器的按钮默认CSS样式比div的not-allowed光标更具体。如果您希望not-allowed光标同时应用于div和子元素,则可以将notAllowed类应用于div并具有此类规则

<强> component.css

 .notAllowed, .notAllowed *
{
  cursor: not-allowed;
}

现在,如果您希望能够动态更改游标,具体取决于某些条件,只需通过将其绑定到条件变量来动态添加该类

<强> component.html

<div class="myClass" [class.notAllowed]="notAllowed ">
        <button class="myButton">
                OK
         </button>
 </div>

<强> component.ts

public notAllowed = true;

我为此

创建了一个stackblitz

https://stackblitz.com/edit/angular-5z9ru4?file=app%2Fapp.component.html

初步回答

为什么不在你的CSS中设置它?

myClass, myClass>*{ cursor: not-allowed;}

或使用

  <div [style.cursor]="'not-allowed'"