Unable to swap out string with text box in TypeScript

I am trying to swap __ with a text box in Angular 2/4. Take a look at the example provided in the link below.

https://stackblitz.com/edit/angular-ajkvyq?file=app%2Fapp.component.ts

Answer №1

Component templates cannot bind unsanitized HTML directly; it must be sanitized first:

constructor(private sanitizer: DomSanitizer) {}

replaceFillBlanks(question): SafeHtml {
  var $inputBox = '<input type="text" name="fillBox"/>';

  let q = this.sanitizer.bypassSecurityTrustHtml(question.replace(/__/g,$inputBox));
  return q;
}

Answer №2

Angular takes measures to secure your HTML content and prevent XSS attacks. Injecting HTML is not as simple as it seems - you need to sanitize it properly.

To safely use HTML content, consider using

bypassSecurityTrustHtml(value: string)
. For more information, refer to the documentation here.

Remember, caution is key. It's crucial to understand the risks involved:

Instances where XSS vulnerabilities can occur should be rare, and extra care is essential to avoid introducing security flaws!

Answer №3

import { Component } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {

  question = "How are you doing today ?. I'm doing well.";

  constructor(private _sanitizer: DomSanitizer){}

  replaceFillBlanks(question){
      var $inputBox = '<input type="text" name="fillBox"/>';

      // if you'll replace any other string except text box this will work fine. 
      //var $inputBox = 'hi';

      let q = question.replace(/__/g,$inputBox);
      console.log(q);
        return this._sanitizer.bypassSecurityTrustHtml(q);
    }
}

Ref: Inject <input> in innerHTML angular 2

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

Display content exclusively within a modal specifically designed for mobile devices

I want to implement a feature where a button triggers a modal displaying content, but only on mobile devices. On desktop, the same content should be displayed in a div without the need for a button or modal. For instance: <div class="container&quo ...

Tips for transferring information to a node server

Currently, I am working with Express and facing the challenge of dynamically sending data to the app.get() method. Specifically, on my index page, there is a list of topics, and upon clicking one, I need to send the name of that element as the required dat ...

Displaying a clock using PHP

Seeking a way to display server time on my website, I have successfully implemented client-side time using JavaScript. How can I now showcase the server time? Are there any ZendFramework classes that can assist with this? Currently, I am utilizing the fo ...

To initiate the development environment, execute the following command: `cross-env NODE_ENV=

[email protected] start /Users/ssurisettii/Documents/il-17g5-app cross-env NODE_ENV=development npm run webpack-development sh: cross-env: command not found npm ERR! code ELIFECYCLE npm ERR! syscall spawn npm ERR! file sh npm ERR! errno ENOENT npm ER ...

Tips on how to send Mongoose response variable in NodeJS Express router res.render?

I just finished setting up a basic Express NodeJS server. My goal is to save the value of the setting returned from mongoose.find() as a variable in res.render, but every time I try, it throws an error saying Cannot read property of undefined. Here' ...

eliminating labels from a string through recursive method

One of my challenges involves developing a function that can remove tags from an input string. For example: '<strong>hello <em>my name <strong>is</strong> </em></strong>' The desired result should be: &apos ...

Only submit the form if all files are selected to prevent any missing files from being uploaded

I am currently utilizing the Vue.js framework along with Axios. Within my HTML page, I have incorporated two separate input fields for selecting an image. Additionally, there is a form present on the page. It's important to note that these inputs and ...

Validation of phone numbers based on country codes

How can I validate phone numbers based on the selected country in Angular? Are there any Angular packages specifically for this task? I've attempted to use regex, but it only works for certain countries. I need a solution that can validate mobile an ...

Converting SVG with an external PNG file embedded into a standalone PNG format using Node

Does anyone know of a node package that can convert an svg file to a png, including external images embedded within the svg code like this? <?xml version="1.0" encoding="utf-8"?> <svg viewBox="0 0 120 120" height="120" width="120" xmlns="h ...

synchronize the exchange of information and events between two components

Just joined this platform and diving into Angular 7 coding, but already facing an issue. I've set up two components along with a service. The data is fetched by the service upon clicking a button in the searchbar component, and I aim to display it i ...

"Sharing fields between mongoose models: How can I reference a field from one model in another

I am currently working on linking specific fields from the User model to the Card schema using the username as a reference point. Let me provide an example using my Card schema: const CardSchema = new mongoose.Schema({ text: { type: String, ...

Fix a typing issue with TypeScript on a coding assistant

I'm struggling with typing a helper function. I need to replace null values in an object with empty strings while preserving the key-value relationships in typescript // from { name: string | undefined url: string | null | undefined icon: ...

My PayPal script (and all other JavaScript) was rendered dysfunctional by Onsen UI

I've been gradually incorporating Onsen UI into my existing web app. Currently, my home page file (index.jade) includes a splitter for navigation within the app. The splitter loads a NodeJS route that renders the requested page in jade. Everything wo ...

How can a div tag and its class be nested using CSS in Angular?

Can someone help me with nesting a div tag with the "error" class in CSS? <div [class]="{error: condition}">{{ message }}</div> I want to know how to have the .error selector inside the div selector in the CSS file. Note: The error ...

Using External APIs in React: A Guide

Recently, I created a React app using the npm module 'create-react-app' I ran into an issue where I needed to call an external API from api.example.com, but found that Axios was making requests to localhost instead of the external API. Here is ...

What steps do I need to take to set up Vue-CLI 3 to generate a webpage with no JavaScript?

My dilemma is this: I have a simple static page that does not require JavaScript. Using vue-cli 3, I am attempting to pass the HTML file through webpack for minification purposes. Unfortunately, it seems that accomplishing this task is not as straightforwa ...

What is the best way to structure a hierarchy in an array or object data using Node.js?

I have the following data arrangement: [{ Country: 'USA', State: 'CA', City: 'LA', District: 'LA-1',Town: 'LA-1,LA-1a,LA_AZ_A',Area: 'Area 51'}, { Country: 'USA', State: 'CA&ap ...

Having trouble with JavaScript concat function not behaving as it should? Can you provide more details to

I am trying to extract all the cities from an object that contains country names as keys and arrays of cities as values. However, my approach seems to be failing and I can't figure out why. var cities = { "United Kingdom": ['london'], ...

Change the value in Vue through a single action (swapping out buttons)

I created a custom component that allows users to add points only once by clicking a button. I want to add an undo option to decrease the point value by 1 after it has been added. When a point is added, I'd like the button to change color to red and d ...

Tips for making jQuery maphilight function properly?

Can someone assist me with Mapilight? I have been trying to get it to work but no success so far. Here are the script links in the head section of my HTML. <script type="text/javascript" src="/js/jquery.js"></script> <script type="text/ja ...