I am having trouble with getting access to my canvas element when its *ngIf condition is satisfied. Here is some context to understand the problem.
In my application, I have a canvas element (that is initially hidden), and a ViewChild element ref variable in my typescript file that accesses the canvas. However, since the canvas is initially not rendered, the ViewChild element ref variable evaluates to undefined. When the ngIf condition evaluates to true, the canvas is finally rendered but the ViewChild element ref variable is not updated. In my code below, a floor plan from a database is loaded when the user chooses it. The canvas will only be rendered once the floor plan is chosen (not null).
How can I get the ViewChild element ref variable to recognize that the canvas is loaded so that it is not undefined when I want to use the canvas?
<div class="row" style="padding-left: 3rem;" *ngIf="floorPlan != null">
<div class="col-lg-6 col-xl-6 col-md-12 col-sm-12" style="text-align: center;">
<canvas (click)="onCanvasClick($event)" style="border: 1px solid lightgray;" #fpCanvas [ngClass]="{over: over}">
</canvas>
</div>
</div>
@Component({
selector: 'app-floor-plan',
templateUrl: './floor-plan.component.html',
styleUrls: ['./floor-plan.component.css']
})
export class FloorPlanComponent implements OnInit, AfterViewInit, AfterViewChecked {
floorPlan: FloorPlan = null;
imagePath : string = "";
@ViewChild('fpCanvas', { static: true }) fpCanvas: ElementRef<HTMLCanvasElement>;
....
constructor(private dataBaseManager: DatabaseManagerService) {
this.dataBaseManager.loadedFloorPlanSubject.subscribe(loaded => {
this.floorPlan = new FloorPlan(loaded);
setTimeout(this.initCanvasAndContext, 2000)
this._image.src = this.floorPlan.getImagePath();
})
....
chooseFloorPlan() {
this.onToggleChooseFloorPlanDialog();
this.dataBaseManager.fetchFloorPlan(this.selectedFloorPlanIndex)
}
}