I'm struggling with accessing my canvas element when its *ngIf condition is met. Let me provide some context to explain the issue.
In my application, there's a canvas element (initially hidden) and a ViewChild element ref variable in my typescript file that accesses the canvas. However, because the canvas isn't rendered initially, the ViewChild element ref variable remains undefined. When the ngIf condition becomes true, the canvas is finally rendered but the ViewChild element ref variable isn't updated accordingly. In the code snippet below, a floor plan is loaded from a database when selected by the user. The canvas will only be displayed once the floor plan is chosen (not null).
How can I make sure that the ViewChild element ref variable recognizes when the canvas is loaded so it's not undefined when attempting 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)
}
}