Issue
I have a component which has an external library component. I want to change toggle one class of external library component based on some condition in my own component. Here thus, I can not use ngClass. I could use document.querySelector but I dont want to use it. Is there any other way?
Solution
You can use ViewChild in your component class to reference the external library component, configuring ViewChild's read
option to give you the component as an ElementRef so you can then toggle the DOM element class.
For example, if the external component in your component's template looks like this:
<div>
<external-component class="toggle-me"></external-component>
</div>
You can attach a template reference variable to it, like so:
<div>
<external-component #exComp class="toggle-me"></external-component>
<!-- ^^ add this template reference variable -->
</div>
Then in your component class, use ViewChild to get a hold of the external component using that template reference variable, specifying { read: ElementRef }
so you get its DOM element rather than its component class instance:
@ViewChild('exComp', { read: ElementRef }) externalComponent: ElementRef;
With that, you can then access the nativeElement
and its classList
to toggle the class:
this.externalComponent.nativeElement.classList.toggle('toggle-me');
Alternatively, if you didn't want to add a template reference variable, or were not able to, you could pass the external component's class name, rather than the template reference variable name, to ViewChild.
@ViewChild(ExternalComponent, { read: ElementRef }) externalComponent: ElementRef;
Here's a StackBlitz showing both options.
Answered By - MikeJ
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.