1

I need to access dom element and manipulate in other class
homeComponent.ts

   import{TableUtility} from "src/shared/table-utility"; 
   export class HomeComponent extends TableUtility{
   constructor(){super()}

homeComponent.html

<button (click)="toggleClass($event)"><img src="img.png"></button>

tableUtility.ts

import{Table} from "primeng/table";
import{Renderer2} from "@angular/core";

export class TableUtility{
constructor(public render:Renderer2)
togglClass(ev){
console.log(this.render.addClass(ev.target,"active");
}

Err:cannot read addClass of undefined

If I use it within home component I can read Renderer2. Can someone tell this with proper reason and how to solve this.

pjay
  • 385
  • 1
  • 3
  • 19

1 Answers1

2

You need to define dependencies in subclass constructor and pass them to superclass via super():

export class HomeComponent extends TableUtility{
constructor(public render:Renderer2){super(render)}
Julius Dzidzevičius
  • 10,775
  • 11
  • 36
  • 81
  • Yeah got it thanks jsbin. Can you explain little bit more about this? – pjay Nov 07 '19 at 06:44
  • Your supper class has dependencies declared in its constructor - `renderer`. When you extend subclass with it, you are able to use all methods of superclass, but they relay on dependencies superclass declares, so it makes sense to require subclass to have those dependencies as well and pass them to superclass via `super()` method. Also, you could pass different dependency from subclass, if types matches, f.ex Renderer3 (just an example to illustrate. Not necessarily would work) – Julius Dzidzevičius Nov 07 '19 at 06:49