2

I'm trying to do inheritance with a class but if I use ViewChild I always get undefined. I'm going to show a simplification of my problem.

I have a parent class like this:

@Component({
  selector: 'parent',
  template: `<h1>Hello {{name}}!</h1> <p #pRef>`,
  styles: [`h1 { font-family: Lato; }`]
})
export class ParentComponent  {
  name: string;
  @ViewChild('pRef') public pRef: ElementRef;

  ngOnInit{
    console.log(this.pRef.nativeElement);
  }
}

And then, I have a child that I want to override name for example:

@Component({
  selector: 'child',
  templateUrl: '<div></div>',
  styleUrls: [ './app.component.css' ]
})
export class ChildCOmponent extends ParentComponent {

name = 'Juan';

}

As I said before, this is a simplification of my problem, but I get the same error that is:

ERROR Error: Cannot read property 'nativeElement' of undefined

I need to access to ViewChild in parent and in child I didn't need it but I get the error because in Child component pRef doesn't exists.

How could I use ViewChild and inheritance at same time?

EchtFettigerKeks
  • 1,692
  • 1
  • 18
  • 33
SantiSori
  • 381
  • 2
  • 15

1 Answers1

1

The problem is that html template is not inherited. Your child class has '' template and there is no #pRef in it On the other hand if you access it in a parent class you will get ElementRef.

Probably a good workaround would be to access the HTMLElement directly using document.getElementById As far as I know, Angular does not allow inheritance of HTML templates for components.

KKulitskiy
  • 11
  • 1