【问题标题】:Angular - How to style Class inside of ng-content?Angular - 如何在 ng-content 中设置类的样式?
【发布时间】:2021-05-06 22:03:25
【问题描述】:

我有这个带有<ng-content> 的文件上传组件。当用户将文件从操作系统悬停到文件上传区域时,组件内的所有标签都从 .fileover 类继承 background-color: rgba(121, 211, 255, 0.15);。但是我无法更改<ng-content> 内部的.ag-center-cols-viewport 的背景颜色。我尝试使用::slotted::ng-deep。最后的图片显示,如果我更改 chrome devtols 内部的颜色,background-color: red; 可以工作。

::ng-deep doc

::slotted doc

任何建议为什么这不起作用?

HTML:

 <div>
            <div class="containerDragDrop" appDnd (fileDropped)="onFileDropped($event)">
              <input class="inputDragDrop file-input" type="file" #fileupload accept="{{accept}}"
                     [disabled]="disabled" multiple
                     (change)="addFiles($event)"/>
                     <ng-content class="fileDropRef"></ng-content>
              <div class="middleFileText">
      </div>
      <label *ngIf="choseFileToggle" class="labelDragDrop" (click)="fileupload.click()">Välj Filer</label>
            </div>
          </div>

带有 ::slotted 的 CSS:

.fileover {
  .middleFileText{
    opacity: 0.8;
  }
  background-color: rgba(121, 211, 255, 0.15);
  :host ::slotted(.ag-center-cols-viewport) {
    background-color: rgba(121, 211, 255, 0.15) !important;
  }
}

带有 ::ng-deep 的 CSS:

.fileover {
  .middleFileText{
    opacity: 0.8;
  }
  background-color: rgba(121, 211, 255, 0.15);
  :host ::ng-deep .ag-center-cols-viewport {
    background-color: rgba(121, 211, 255, 0.15) !important;
  }
}

【问题讨论】:

    标签: html css angular


    【解决方案1】:

    我缺少一些有关您的 html 代码所在位置以及 ag-center-cols-viewport 是什么的信息,但我认为您确实将其添加到组件中。假设 my.component.html 和 ag-center col 已导入您的 @NgModule

    注意:::ng-deepdeprecated,在以后的angular版本中会被移除,请不要再使用了

    my.component.ts 中添加以下内容

    @Component({
      selector: 'my-component',
      templateUrl: './my.component.html',
      styleUrls: ['./my.component.scss'],
      encapsulation: ViewEncapsulation.None, // <-- Here, we remove the style encapsulation
    })
    

    加上你的my.component.scss 然后这样写

     my-component { // Name of your selector
      .fileover {
      .middleFileText{
        opacity: 0.8;
      }
      background-color: rgba(121, 211, 255, 0.15);
      .ag-center-cols-viewport {
        background-color: rgba(121, 211, 255, 0.15) !important;
      }
    }
    }
    

    如果这不起作用,可能是因为您使用的组件确实在更高级别加载代码,这意味着代码不在您的组件内,而是在外部,添加到 DOM 中的某个位置。

    为了能够使用 css 进行更改,您必须将全局 css 添加到位于 src 文件夹根目录的 style.css

    .ag-center-cols-viewport {
        background-color: rgba(121, 211, 255, 0.15) !important;
    }
    

    如果您不希望 css 全局更改,那么您应该找到一种方法将一些自定义 css 类名称添加到 ag-center-cols-viewport

    【讨论】:

      猜你喜欢
      • 2017-04-26
      • 2019-09-29
      • 2017-02-04
      • 2018-11-04
      • 2016-04-11
      • 2013-10-29
      • 1970-01-01
      • 2019-03-04
      • 1970-01-01
      相关资源
      最近更新 更多