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

Component remains populated even after values have been reset

My child component is structured as shown below, ChildComponent.html <div> <button type="button" data-toggle="dropdown" aria-haspopup="true" (click)="toggleDropdown()"> {{ selectedItemName }} <span></span> </but ...

What are the steps for executing an API and entering data into it?

I have developed an API using NodeJS, ExpressJS and MongoDB to filter and sort school data based on location and fees. The main code snippet looks like this: const express = require('express'); const bodyparser = require('body-parser') ...

Developing in Java Script with ENVDTE involves adding a new project to an existing solution and placing it in a designated sub-folder for organization purposes

Currently, I am working on developing a Visual Studio extension for a new C++ project template using Visual Studio 2010. The approach I am taking involves utilizing the .vsz template method and customizing the default.js code to suit my requirements. Withi ...

Obtain JavaScript object from WebView in Swift

Currently, I am displaying a webView in my iOS app using Swift. My goal is to retrieve an object from the JavaScript code within the webView. Upon inspecting the console, I discovered that the desired object is named "window.user". However, when attempti ...

What are some ways to implement querySelectorAll in conjunction with htmx?

I'm currently using htmx, an amazing library with a small issue that I'm struggling to resolve. htmx utilizes querySelector to find elements for swapping or updating, for example with hx-swap="...", hx-target="...". How can I use querySelectorAll ...

Component designed to be reusable across multiple different Angular 8 applications

I have multiple components with similar logic. Take for example: import { Component, OnInit } from '@angular/core'; import { Rule } from '@models'; import { ConfirmationDialogComponent } from '@core'; import { RulesSaveCompo ...

In certain situations, Chrome and Safari fail to trigger the unload function

Struggling with a persistent issue lately and really in need of some assistance. My goal is to perform a server-side callback to clear certain objects when the user navigates away from our page, without needing to click logout. Due to business requirements ...

The Angular data table is encountering an issue as the dataStream.pipe function is not recognized

I'm currently working on setting up a table using Angular data table, but I've run into an issue related to the dataSource. I'm seeing an error message that says "dataStream.pipe is not a function", and I'm having trouble resolving it. ...

Unable to retrieve content in NGX-Quill upon submission

I am currently using "ngx-quill": "^14.3.0" along with "@angular/core": "~12.2.0". It is registered in the app module: QuillModule (not for root). And also in the lazy loaded module: QuillModule (not for root). public editor = { toolbar: [ ...

The issue of underscorejs being undefined arises when trying to load it using both XMLHttpRequest and

I am attempting to dynamically load underscorejs using XMLHttpRequest and eval function function includeScriptSync(scriptUrl) { var xmlhttp = new XMLHttpRequest(); xmlhttp.open("GET", scriptUrl, false); xmlhttp.onreadystatechange = function() ...

"Discrepancy in results between JSON stringify and JavaScript object conversion

I need to save this object in a database, but first I have to send it to the backend. Recorder {config: Object, recording: false, callbacks: Object, context: AudioContext, node: ScriptProcessorNode…} However, after using JSON.stringify(recorder) The r ...

Tips for leveraging async and await within actions on google and API integration

Currently, I am developing an Actions on Google project that utilizes an API. To handle the API calls, I am using request promise for implementation. Upon testing the API call, I observed that it takes approximately 0.5 seconds to retrieve the data. Theref ...

Experiencing an array of issues while attempting to convert my HTTP request into an

I am currently facing some difficulties in converting my HTTP requests into observables. Within my Angular App, there is a service called API Service which takes care of handling all the requests to the backend. Then, for each component, I have a separate ...

Utilize the pipe function to generate a personalized component

I have incorporated a custom pipe in my Angular 2 application to parse and make URLs clickable within messages displayed using an ngFor loop. If the URL links to a YouTube video, I also convert it into embed code. To optimize performance, I am looking to ...

Compatibility issues arise with static properties in three.d.ts when using the most recent version of TypeScript

When compiling three.d.ts (which can be found at this link) using the TypeScript develop branch, an error occurs with the following message: Types of static property 'Utils' of class 'THREE.Shape' and class 'THREE.Path' are i ...

Is it permissible to use multiple JWT tokens in the HTTP header?

Currently, I have implemented the jwt access and refresh token pattern for client-server communication. The method involves sending two jwt tokens in the header: the access token and the refresh token. This is done by adding the following code to the heade ...

What is the list of NPM packages already included in the AWS Lambda execution environment?

I was surprised to discover that the aws-sdk NPM module comes preinstalled in AWS Lambda using nodejs8.10. I couldn't find any information online about this. Are there other node.js modules that are also pre-installed in AWS Lambda? ...

After a loop, a TypeScript promise will be returned

I am facing a challenge in returning after all calls to an external service are completed. My current code processes through the for loop too quickly and returns prematurely. Using 'promise.all' is not an option here since I require values obtain ...

Unable to display an image prior to its upload

I'm facing an issue with changing the image for my second data. It's not updating, but when I try it with the first data, it works fine. I'm unsure why this is happening and would appreciate any help in resolving it. Here is the form where ...

Error: Unable to access property 'camera' as it is undefined

After implementing the Raycaster from Three js to detect collision following a MouseMove event, I encountered an error: Cannot read properties of undefined (reading 'camera') Here is the code snippet causing the issue: bindIFrameMousemove(if ...