If you wish to reference an external library component in your Angular component class, you can utilize the ViewChild decorator. By setting the read
option of ViewChild to obtain the component as an ElementRef, you will gain access to toggle the class of the DOM element.
For instance, if the external component within your component's template is structured as follows:
<div>
<external-component class="toggle-me"></external-component>
</div>
You can assign a template reference variable to it like this:
<div>
<external-component #exComp class="toggle-me"></external-component>
<!-- ^^ add this template reference variable -->
</div>
Next, within your component class, employ ViewChild to obtain the external component using the specified template reference variable while specifying { read: ElementRef }
to retrieve its actual DOM element instead of its class instance:
@ViewChild('exComp', { read: ElementRef }) externalComponent: ElementRef;
Subsequently, you can then manipulate the nativeElement
and its
classList</code property to toggle the designated class:</p>
<pre class="language-js"><code>this.externalComponent.nativeElement.classList.toggle('toggle-me');
In another scenario where adding a template reference variable is not feasible, you have the alternative of passing the class name of the external component to ViewChild rather than the variable name:
@ViewChild(ExternalComponent, { read: ElementRef }) externalComponent: ElementRef;
To observe these strategies in action, refer to this StackBlitz example.