Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>;
like image 334
Diemauerdk Avatar asked Feb 06 '26 23:02

Diemauerdk


2 Answers

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 }

like image 94
Amir Fawzy Avatar answered Feb 09 '26 12:02

Amir Fawzy


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 😊

like image 34
hghandi Avatar answered Feb 09 '26 12:02

hghandi