Diemauerdk
Diemauerdk

Reputation: 5938

How to change a CSS class using Angular 7

I am using ngx-bootstrap's modals and I want to change the CSS class modal-dialog with some other properties.

My question is: How do I dynamically change the properties of for example this class in Angular?

I have played around with ElementRef, TemplateRef and Rendere2 but not found any solution.

Thanks for you help in advance.

EDIT 1:

I am opening the modal using BsModalService, so my template looks like this:

<ng-template #defaultModalTemplate>
    Content
</ng-template>

I open the dialog like this:

public openModal(): void {
    this.modalRef = this.modalService.show(this.templateRef);

    if (this.renderer && this.templateRef) { // trying to extract .modal-dialog here

    }
}

the variable templateRef is defined like this:

@ViewChild('defaultModalTemplate') public templateRef?: TemplateRef<any>;

Upvotes: 2

Views: 15364

Answers (2)

hghandi
hghandi

Reputation: 114

I did need to use this just now, and found a way that worked for me. What you can do is like this:

    <div class="{{className}}">
     Content
    </div>

and Whenever you change the value of the class it will be applicated on the DOM.

You can initialize the variable className with whatever class you want and then change it to whatever class you want afterwards. This is an application for Multi-Theme, there are more things you can do with this like making a service and changing the class in another component and then send that className to the component where you change the class and then theme changed.

Happy Coding 😊

Upvotes: 2

Amir Fawzy
Amir Fawzy

Reputation: 468

you can do that by class binding or NgClass

<div [class.className]="proerty(boolean)">some text or elements</div>

property here if it true will active/add the class false deactivate/remove

or

<div [ngClass]="{'className': expiration }">some text or elements</div>

with this approach you can use more than class and control them by expiration all you need to do separate them by , like so {'className': expiration, 'anotherClass': expiration }

Upvotes: 6

Related Questions