繁体   English   中英

在 ngOnInit 和 ngOnDestroy 组件时添加和删除 css 样式

[英]add and remove the css style when ngOnInit and ngOnDestroythe component

我为预览文件audiovideo 、. . . 我正在为此使用材质对话框。

我需要打开对话框时,背景是透明的。

我在scss组件中使用此代码:

::ng-deep .mat-dialog-container {
    background-color: transparent !important;
  }

它在所有对话框中都有,但我只需要在这个组件中使用对话框。

在下一步中,我尝试使用此代码将此样式仅用于此组件:

@Injectable({
    providedIn: 'root'
})

export class StyleService {
    private stylesMap: Map<any, Node> = new Map();
    private host: Node;

    constructor() {
        this.host = document.head;
    }

    private createStyleNode(content: string): Node {
        const styleEl = document.createElement('style');
        styleEl.textContent = content;
        return styleEl;
    }

    addStyle(key: any, style: string): void {
        const styleEl = this.createStyleNode(style);
        this.stylesMap.set(key, styleEl);
        this.host.appendChild(styleEl);
    }

    removeStyle(key: any): void {
        console.log('in')
        const styleEl = this.stylesMap.get(key);
        console.log(styleEl);
        if (styleEl) {
            this.stylesMap.delete(key);
            this.host.removeChild(styleEl);
        }
    }
}

并以这种方式在组件中使用它:

  constructor(
    , private styleService: StyleService) {}

ngOnInit(): void {
    this.styleService.addStyle('transparent-dialog-theme', require('../../them/dialogStyle.scss'));
}



   ngOnDestroy(): void {
    this.styleService.removeStyle('transparent-dialog-theme');
  }

但它对我不起作用(此组件没有透明对话框)。

有什么问题? 我怎么解决这个问题???

如果您想在任何特定情况下将特定样式应用于对话框的背景,您可以使用配置将 class 添加到背景。

例如 -

let dialogRef = this.dialog.open(ExampleDialogComponent, {
      width: '250px',
      data: { name: this.name, animal: this.animal },
      backdropClass: 'dialog-bg-trans'
    });

在您的全局样式中,您可以添加该样式 -

.dialog-bg-trans {
  background-color: transparent;
}

您可以仅在您想要行为的地方提供此配置,而不是在其他地方。

请参考这个 - https://stackblitz.com/edit/ab-angular-mat-dialog-bg-color?file=app%2Fexample%2Fexample.component.ts

希望它会有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM