The sanitizer variable becomes null when accessed outside of the NgOnInit function in Angular using TypeScript

At first, I added DomSanitizer to the component:

import { DomSanitizer, SafeResourceUrl} from '@angular/platform-browser';

Next, a class was created and included in the constructor:

 export class BlocklyComponent implements OnInit {
      primaryWorkspace: Blockly.WorkspaceSvg;
      GEE = "PCFET0NUWVBFIGh0bWw+Cgo8aGVhZD4KPG1ldGEgY29udGVudD0idGV4dC9odG1sOyBjaGFyc...";
    public geeMap: SafeResourceUrl;
      constructor(private sanitizer: DomSanitizer) {}
ngOnInit() {

The NgOnInit function runs correctly, but the updateURL function (outside of NgOnInit but inside the class) throws an error stating that this.sanitizer is undefined:

//Creates de src that has to be in the iframe. What I need to do is to update this safeResourceUrl.
        this.geeMap = this.sanitizer.bypassSecurityTrustResourceUrl(`data:text/html;base64,${this.GEE}`);

        //Reads the events in a workspace. When it notices a change, it triggers the updateURL function

        primaryWorkspace.addChangeListener(this.updateURL);

      }
      updateURL(primaryEvent) 
         {
          if (primaryEvent.isUiEvent) {
            return; //Do not clone ui events 
          };
          console.log('hola');
         //Problem. Here it sais that this.sanitizer is undefined.
          this.geeMap = this.sanitizer.bypassSecurityTrustResourceUrl(`data:text/html;base64,${this.GEE}`);
        }

This issue is familiar and I have encountered it multiple times before, however, I am currently unsure how to resolve it. I have searched various forums for a solution to the undefined problem without success. Thank you kindly

Answer №1

When stepping outside of the typical Angular event binding flow, there are two ways to ensure the correct reference to this when adding an event listener:

Using arrow functions (inside ngOnInit):

primaryWorkspace.addChangeListener((event)=>this.updateURL(event));

Using .bind method (inside constructor):

this.updateURL = this.updateURL.bind(this);

Then in the ngOnInit function:

primaryWorkspace.addChangeListener(this.updateURL);

It's also worth noting that you may have intended to use addEventListener('change',...) instead of addChangeListener.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Incorrect dimensions of a-scene. Utilizing a-frame and ar.js in combination with Vue on the ionic framework

I am currently exploring an AR project using Vue and Ionic. I have been utilizing A-Frame with Ar.js, which has provided a partial video output on my iPhone device. However, the video only covers 1/3 of the screen width, leaving the rest blank. How can I a ...

Struggling to transfer array data from service to component

I am currently working on passing an array from service.ts to a component. My goal is to display the array elements in a dialog box. However, I encountered a Typescript error TypeError: Cannot read property 'departmentArr' of undefined. I am str ...

The system is unable to locate the module at 'C:UsersSanjaiAppDataRoaming pm ode_modulesprotractorinprotractor'. This error originates from internal/modules/cjs/loader.js at line 960

After running "protractor conf.js" without any issues, I decided to install protractor globally using the command "npm install -g protractor". However, after installing protractor globally, I encountered the following error message: internal/modules/cjs/lo ...

Storing JSON data in LocalStorage or within the App on Ionic 2

I am currently in the process of developing a mobile app for both IOS and Android platforms. The app will feature a list of objects including images, names, etc., which are stored on a backend server powered by node.js. My goal is to allow users of the ap ...

How to trigger a click event in React using TypeScript and material-ui library

Currently, I am facing an issue when trying to update the value of material-ui TextFields from the store. When manually typing inside the field, everything works fine as expected with the handleChange() and handleBlur() functions handling the events. Howev ...

The ng-change event fails to trigger when the date change event is activated

Hey there, I'm new to working with AngularJS. I have a scenario where I want a method to be triggered when I change the date, opening a modal. However, when I use the ng-change event, the method is not called upon date change. If I switch to using ng- ...

Can parameters with identical union types in a function signature be streamlined to contain only the exact same subtypes using generic types?

// defining a type Combinable with string or number as possible values type Combinable = string | number; // function to check if parameter is a string function isString(param: unknown): param is string { return typeof param === "string"; } /** * Func ...

Using an alias to call a function defined in a separate module in TypeScript

The following code snippet is from the v4.js file located inside the uuid folder within Angular's node_modules: var rng = require('./lib/rng'); var bytesToUuid = require('./lib/bytesToUuid'); function v4(options, buf, offset) { ...

Choosing the initial object in Angular2 using ngValue

Currently, I am encountering an issue where the initial value is not being set or updated when populating a select element with data from a REST source within my component. To populate the select list, I retrieve the country data as follows: ... ngOnInit ...

Is there a way to change the data type of all parameters in a function to a specific type?

I recently created a clamp function to restrict values within a specified range. (I'm sure most of you are familiar with what a clamp function does) Here is the function I came up with (using TS) function clamp(value: number, min: number, max: number ...

Challenges with TypeScript build in DevOps related to Material UI Box Component

Currently, I am facing an issue while trying to build a front end React Typescript application using Material ui in my build pipeline on Azure DevOps. The problem seems to be related to the code for the Material ui library. Despite successfully building th ...

In <R>, what does R represent when it is wrapped around an observer of type Observer<R>? Would it result in a Subscription, Function, or void?

The Angularfire2 project is in the process of adding a storage feature through a work-in-progress branch. This implementation includes two new files - an Observable class and a Factory function. Observable class export class FirebaseUploadTaskObservable& ...

leveraging the tsconfig path for the source directory in the Next.js Image component

I'm attempting to store the path of my assets folder in the tsconfig file and then use it in the src attribute of the Image component, but for some reason it's unable to locate the address! This is what's in my tsconfig.js file: "paths ...

Steps for updating the same array in TypeScript

I have written a reducer code where I check if the same value is already present in the array. If it is, I update the previous value instead of pushing the same value again. Here is my code snippet: export function reducer( state: IDeviceState = ...

What's the best way to process a string array using iteration in Typescript?

I have an array of colors: colors = ['red','blue','purple']; I would like to display the following message: colors in ('red','blue','purple') When I tried to achieve this using forEach metho ...

Having trouble updating properties of child components in Angular

I have a data filtering functionality where I enter values in a filter popup and successfully retrieve results. I then store this data in local storage to retain it when navigating back from another page. However, upon returning to the filter component, I ...

Using PrimeNG checkboxes to bind objects in a datatable

PrimeFaces Checkbox In the code snippet below, my goal is to add objects to an array named selectedComponents in a model-driven form when checkboxes are checked. The object type of item1 is CampaignProductModel, which belongs to an array called selectedC ...

What is the method for accessing the string value of a component's input attribute binding in Angular 2?

In my Angular2 application, I have a straightforward form input component with an @Input binding pointing to the attribute [dataProperty]. The [dataProperty] attribute holds a string value of this format: [dataProperty]="modelObject.childObj.prop". The mod ...

Angular Table with sort, pagination, and search functionalities

ts file import { Component, OnInit, ViewChild } from '@angular/core'; import { MatPaginator } from '@angular/material/paginator'; import { MatSort } from '@angular/material/sort'; import { MatTableDataSource } fr ...

How to Share Angular Modules Between Two Projects with Ivy Compilation Necessity

Query: I am faced with the challenge of sharing common modules between two Angular projects, one of which requires full Ivy compilation to function properly. To manage these shared resources, we have set up a private GitHub NPM repository. However, becaus ...