Way to add custom class when using ngx-bootstrap modalService

老子叫甜甜 提交于 2021-02-06 02:34:55

问题


When looking to the ngx-bootstrap source code here:

modal-options.class.ts

There is an optional class property defined as class?: string;.

What is the way to use it ?

Is it possible to add a custom class like:

this.modalService.config.class = 'myClass';

Before using the servive as for example:

this.modalRef = this.modalService.show(template, {
  animated: false
});

This way, I think we can add custom CSS to the displayed modal

I've tried to add a custom class without success.

That class property is not an array, if applicable, does it mean that we can only add one custom class ?

Demo: by adding and overriding the modal class, the modal is not showing

https://stackblitz.com/edit/ngx-bootstrap-3auk5l?file=app%2Fapp.component.ts

Adding the modal class this way do not help:

this.modalRef = this.modalService.show(template, Object.assign({},
                this.config, { class: 'gray modal-lg modal' }));

https://stackblitz.com/edit/ngx-bootstrap-awmkrc?file=app%2Fapp.component.ts


回答1:


According to the ngx-bootstrap documentation about the Modal component (see the component tab), you can add a class member to the config object.

Important: Since the modal element is outside of the component element in the rendered HTML, the CSS encapsulation should be turned off for the component, or the style attributes for the class should be specified in another file, to make sure that the styles are applied to the modal element.

The code snippet below can be executed in this stackblitz.

import { Component, TemplateRef, ViewEncapsulation } from '@angular/core';
import { BsModalService, BsModalRef } from 'ngx-bootstrap';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class AppComponent {
  modalRef: BsModalRef;
  config = {
    animated: true,
    keyboard: true,
    backdrop: true,
    ignoreBackdropClick: false,
    class: "my-modal"
  };

  constructor(private modalService: BsModalService) { }

  openModal(template: TemplateRef<any>) {
    this.modalRef = this.modalService.show(template, this.config);
  }
}

with a CSS file like this:

.my-modal {
  border: solid 4px blue;
}

.my-modal .modal-header {
  background-color: lime;
}

.my-modal .modal-body {
  background-color: orange;
}

Update: This other stackblitz shows an example of CSS styles imported from an external file into styles.css, allowing to keep the CSS encapsulation in the component.



来源:https://stackoverflow.com/questions/47957036/way-to-add-custom-class-when-using-ngx-bootstrap-modalservice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!