Issue
I really need help to solve this error. I wrote the following JavaScript code below to enable my tab indicator to show on a clicked tab when clicked on but all I am getting is an error which says: "Property 'style' doesn't exist on type 'Element'". The tabs work perfectly fine, I can switch from one tab to the other. I have seen similar questions but my issue wasn't resolved following their lead suggestions. I am currently building an angular project and i wrote my JavaScript in the ngInit(){} function in my .ts file. The code is below:
ngOnInit() {
let tabPanes = this._class('tab-header')[0].getElementsByTagName('div');
for (let i = 0; i < tabPanes.length; i++) {
tabPanes[i].addEventListener('click', () => {
this._class('tab-header')[0]
.getElementsByClassName('active')[0]
.classList.remove('active');
tabPanes[i].classList.add("active");
this._class('tab-indicator')[0].style.top = 'calc(80px + ${i*50}px)'; // This flags a "property 'style' doe not exist on type 'Element'" error.
this._class('tab-content')[0]
.getElementsByClassName('active')[0]
.classList.remove('active');
this._class('tab-content')[0]
.getElementsByTagName('div')[i]
.classList.add('active');
});
}
}
_class(name: any) {
return document.getElementsByClassName(name);
}
Where did i go wrong? Any idea on how to solve this?
Solution
getElementsByClassName
returns an HTMLCollectionOf<Element>
. There is no style
property on Element type and hence the error.
You can type cast it to collection of HTMLElement and that should resolve the issue:
_class(name: any): HTMLCollectionOf<HTMLElement> {
return document.getElementsByClassName(name) as HTMLCollectionOf<HTMLElement>;
}
PS: Though the above should resolve the typescript error, but as Eliseo mentioned in one of the comments, you can make use of Angular event binding and property binding to class attribute to do it Angular way.
Answered By - Siddhant
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.