angularangularjs-ng-class

ngClass add a class to element A if element B exists in DOM?


I want to use ngClass to add a class to an element if another element exists in the DOM.

<div id="element-a" 
     [ngClass]="{'my-class':(expression-to-check-if-#element-b-exists)}">
     ...
</div>

<div id="element-b">I'm here!</div>

Is this possible to do directly in the template, or do I need to something more complex in the component?


Solution

  • You need to do more something in the component. It is not complex, just one line of code.

    Easiest way:

    1. You can use *ngIf to conditionally display an element (element b)
    2. expression-to-check-if-#element-b-exists needs to bind on something. Have it pointing to the same property than b. Voila.

    I will update this answer with more complex options if this doesn't suit your original need.