Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

With Angular how to fill the canvas of a base component from a child component using template inheritance

I have a base component with a canvas in it. I can fill the canvas a solid colour in the ngOnInit method of this base class.

I have a child component which inherits the template of the base. I try to call the base’s canvas fill method from the child’s ngAfterViewInit method but it says that the canvas element is null.

I have put in alert messages and they are coming up in the order I expect. The first is in the ngOnInit method of the base and the second in the base’s fillCanvas method which I call from the child’s ngAfterViewInit method.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I have the code in StackBlitz here:

Code Example

Can anyone help show me what I have done wrong \ need to do so as to be able to achieve filling of the canvas from the child?

>Solution :

I dont think you need inheritance here, you can just call the function from the viewChild of that element, example below!

child

import { ViewChild } from '@angular/core';
import { Component, AfterViewInit } from '@angular/core';
import { BaseComponent } from '../base/base.component';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
})
export class ChildComponent implements AfterViewInit {
  @ViewChild(BaseComponent) base: BaseComponent;
  constructor() {}

  ngAfterViewInit() {
    this.base.fillCanvas();
  }
}

child html

<app-base [templateRef]="childTemplate"></app-base>

<ng-template #childTemplate> Child's extended template </ng-template>

stackblitz

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading