Steps for Cleaning a Property within an Angular 2 Model Class

In my model class, I am working with a property called thumbnailUrl which contains the URL of an image on a different domain. Due to this, it needs to be sanitized before being rendered in the component's template. To achieve this, I have introduced a new property named thubnailStyleUrl which is intended to return the sanitized style (SafeStyle) for use as a background-image in the template.

However, upon running the code, I encounter the following error:

The error message states: 'Cannot read property 'bypassSecurityTrustStyle' of undefined.'

I am attempting to inject DomSanitizer into the constructor of my model class as shown below. Is it possible to do so? If not, what alternative options exist for me to sanitize this property before rendering it?

This is how my model class looks like...

import {DomSanitizer, SafeStyle} from "@angular/platform-browser";

export class RecentOrderModel {

    constructor(dataModel:any, private _sanitizer: DomSanitizer) {
        this.orderNum = dataModel.orderNum;
        this.poNum = dataModel.poNum;
        this.buyerName = dataModel.buyerName;
        this.thumbnailUrl = dataModel.thumbnailUrl;
    }

    public get thumbnailStyleUrl() :SafeStyle {
        return this._sanitizer.bypassSecurityTrustStyle('url('+this.thumbnailUrl+')');
    }

    orderNum:string;
    poNum:string;
    buyerName:string;
    thumbnailUrl:string;


}

Answer №1

Having dependency injection is not possible if you instantiate the model like this:

new RecentOrderModel();

However, if you call it from a service or a component, you can structure it in the following way:

@Injectable()
export class RecentOrderFactory {

    constructor(private _sanitizer: DomSanitizer) {}

    public createOrderModel(datamodel: any): RecentOrderModel {
        return new RecentOrderModel(datamodel, this._sanitizer);
    }

}

To make use of this factory, you need to add it to your providers array.

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

The testString's dependencies are unresolved by Nest

Encountered Problem: Facing the following issue while running a unit test case Nest is unable to resolve the dependencies of the testString (?). Please ensure that the argument SECRET_MANAGER_SERVICE at index [0] is available in the context of SecretMa ...

Discovering items located within other items

I am currently attempting to search through an object array in order to find any objects that contain the specific object I am seeking. Once found, I want to assign it to a variable. The interface being used is for an array of countries, each containing i ...

Intelligent Table: Sorting Based on Conditions

Is it possible to implement conditional st-sort in smart-table? For instance, suppose I have an array that specifies the sortable columns in my table. Let's say my table has columns [FirstName, LastName, Age, email] and my sorters array is [firstName, ...

Tips for stopping TypeScript code blocks from being compiled by the Angular AOT Webpack plugin

Is there a way to exclude specific code from Angular's AOT compiler? For instance, the webpack-strip-block loader can be utilized to eliminate code between comments during production. export class SomeComponent implements OnInit { ngOnInit() { ...

Getting permission for geoLocation service on iOS in Ionic: A step-by-step guide

I have recently developed a social media application that utilizes geoLocation services. The app is built with Ionic 4 and has a Firebase backend. While the GeoLocation services are functioning properly on Android devices, users of iOS are not being prompt ...

The Webstorm AngularJS extension appears to be malfunctioning, as it is not able to recognize the keyword 'angular'

As a beginner in Angularjs and web development, I have been using Webstorm to develop my projects. I have already installed the Angularjs plugin, which seems to be working fine in my HTML files. However, I am facing an issue with my .js file. In this file, ...

Identifying the web browser by utilizing the UserAgent detection method

How can I determine if the current browser is Chrome using TypeScript/JavaScript? I previously used the following method: var isChrome = !!(<any>window).chrome && !!(<any>window).chrome.webstore; However, this doesn't work anymo ...

The matHeaderRowDef property binding is not being utilized by any directive within the embedded template

Check out the HTML table below: <mat-table matSort class="inbox__messages" #table [dataSource]="dataSource"> <!-- Creating Column --> <ng-container matColumnDef="building"> <mat-header-cell *matHeaderCe ...

Getting values from a PHP page into an Angular JS controller is a straightforward process that involves passing data

Currently in the process of integrating the payumoney gateway and receiving responses in PHP. However, I am looking to trigger an API based on this response in order to send an invoice via email using AngularJS. Below is a snippet of my PHP code: <?php ...

Is it possible to directly call the Watch function from the controller?

Is it possible to manually trigger the watch function in the controller? Requirements: There are currently two nested tree structured checkboxes in AngularJS - one for carriergroups and another for modes. The mode values are dependent on the selected car ...

After receiving a data token from the server in one controller, how can I efficiently utilize that token in a different AngularJS controller?

In my adminSearchCtrl controller, I am receiving data from the server in the form of a token and want to pass that token to another controller named "adminViewCtrl". How can I achieve this? adminSearchCtrl.js $scope.getUserDetails = function(selectedUser ...

Identifying hyperlinks in Angular JS: A complete guide

I am using Angular JS for my chat functionality. I want to prompt a dialog window to open when a user enters a URL like this: /chat/dialog/12 Can someone please advise on how to achieve this? ...

Converting a JSON array stored in a local file to a TypeScript array within an Angular 5 project

I'm currently working on developing a web app using Angular 5. My JSON file has the following structure: [ { "id": 0, "title": "Some title" }, { "id": 1, "title": "Some title" }, ... ] The JSON file is store ...

When placed above in the template, the ng-model is causing the ng-repeat to not display anything

Currently, I am teaching myself Angular by following a tutorial at https://docs.angularjs.org/tutorial, but with my twist of using different data to keep things interesting. My struggle seems to stem from a simple mistake I might be making, compounded by ...

You can't observe the behavior of simulated functions in a class with a manually created mock

Kindly note that I have set up a comprehensive Github repository where you can download and explore the content yourself here I am currently working on mocking a non-default exported class within a module using a manual mock placed in the folder __mocks__ ...

Best practices for utilizing ngrx/store in Angular 2

As I am refactoring my Angular 2 applications to follow the ngrx pattern, some questions have arisen in my mind: My application retrieves a list of apps and a list of app categories. Can I manage state like "selectedCategory" (where only one can be select ...

Prevent redirection on buttons within ionic lists

THE ISSUE: I am facing an issue in my Ionic app where I am using the ion-list component. Each item in the list can be swiped to reveal a button (add/remove to favorites). Additionally, each item serves as a link to another page. The problem arises when ...

What's the best way to refactor the `await nextEvent(element, 'mousemove')` pattern in my code once it is no longer necessary?

Within my React component, the code includes the following: class MyComponent extends React.Component { // ... trackStats = false componentDidMount() { this.monitorActivity() } componentWillUnmount() { this.trackStat ...

State hook variable not being properly updated within a functional component

After updating the name of an ingredient, I am looking to save this data as an ingredient with the new name: from "Milk" to "Cow's milk". I've included simple steps (1,2,3) in comments to outline the process briefly, but for clarification, assum ...

Issues with displaying Angular Material's ng-messages in a dialog box

While working on a login form within a dialog, I noticed that the ng-messages for the respective input are not appearing. The validation is functioning properly as the input turns red when there's an error, and the button remains disabled until the va ...