Unable to retrieve template generated using the innerHTML directive in Angular 4

I am in need of accessing the elements of a dynamically created component's DOM through the innerHTML directive in Angular. Below is my main component:

import {Component} from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <app-block [template]="template"></app-block>
  `
})
export class AppComponent {

protected template = `
      <main role="main" class="inner cover">
        <h1 class="cover-heading text-center">Cover your page.</h1>
        <p #paragraph class="lead">Cover is a one-page template for building simple and beautiful home pages. 
        Download, edit the text, and add your own fullscreen background photo to make it your own.</p>
        <p #paragraph class="lead">
          <a href="#" class="btn btn-lg btn-secondary">Learn more</a>
        </p>
      </main>
  `;
}

And here is the dynamically created component:

import {
  AfterViewInit,
  Component,
  Input,
  ViewChildren,
 } from '@angular/core';

@Component({
  selector: 'app-block',
  template: `    
    <div [innerHTML]="template"></div>
  `
})
export class BlockComponent implements AfterViewInit {
  @Input() template: String;
  @ViewChildren('paragraph') ps;

  public ngAfterViewInit(): void {
    console.log(this.ps.length);
  }
}

When I tried to get the length of my object, it appeared to be empty as if it couldn't detect the auto-generated template.

Answer №1

Angular has a default setting that restricts the injection of dynamic HTML into the template due to security concerns like Cross Site Scripting. You can read more about this on this page.

To work around this restriction, you can follow the instructions in the linked documentation. One simple solution is to use a pipe:

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

@Pipe({name: 'safeHTML'})
export class SanitizeHtml implements PipeTransform {
  constructor(private sanitizer: DomSanitizer) {}

  transform(html): SafeHtml {
    return this.sanitizer.bypassSecurityTrustHtml(html);
  }
}

You can then incorporate this pipe into your template as follows:

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

RxJS: Transforming an Observable array prior to subscribing

I am retrieving data (students through getStudents()) from an API that returns an Observable. Within this result, I need to obtain data from two different tables and merge the information. Below are my simplified interfaces: export interface student Stude ...

Tips for utilizing jQuery to check for a value within an input field?

Hey there! I'm currently teaching myself jQuery in order to achieve a specific effect. I'll do my best to explain my issue, but please bear with me as English is not my first language. My current goal is to create an input field that will disapp ...

Nesting two ngFor loops in Angular using the async pipe leads to consistent reloading of data

In my Angular application, I am trying to retrieve a list of parent elements and then for each parent, fetch its corresponding children (1 parent to n children). Parent Child1 Child2 Parent Child1 Parent3 Child1 Child2 Child3 Initially, I succes ...

After a postback, the Javascript function removes the displayed div

I am facing an issue with a page containing a button that uses JavaScript to display the content of a div. I also have an ASP.net validator control that triggers a postback. When I debug the JavaScript in Firebug, the div remains visible; however, if I all ...

How to resolve undefined Axios Authorization headers in Vue.JS and Node.JS interactions?

Encountering an issue while trying to set authorization headers for my axios instance. Here is the code snippet from my Vue.JS application running on http://localhost:8080 : axios.defaults.headers.common['Authorization'] = 'Bearer ' ...

Generate a Jade/Pug template using a JavaScript variable

I've been encountering some difficulties with Pug (Jade) recently. I'm passing an array from the backend to the frontend and then sorting it on the client side. Here's how it looks: potentials is the array of objects that I'm sending ...

What is the best way to showcase the user's input on the screen

Can anyone assist me in showing my user input from various types of form elements like textboxes, radio buttons, checkboxes, and dropdowns in a JavaScript alert box upon clicking the submit button? I am struggling to figure out how to achieve this function ...

Utilizing Angular 8's Reactive Form to Transform Checkbox Event Output into a String Format

My form is reactive and includes a field called Status, which can have the values 'A' or 'I': this.form = this.formBuilder.group({ result_info: this.formBuilder.array([ this.getResultcontrols()]), stat ...

Executing a function defined in a .ts file within HTML through a <script> tag

I am attempting to invoke a doThis() function from my HTML after it has been dynamically generated using a <script>. Since the script is loaded from an external URL, I need to include it using a variable in my .ts file. The script executes successfu ...

Combining two JSON objects using Angular's ng-repeat

My goal is to extract data from two JSON files and present it in a table: The first file 'names.json' contains: [ { "name": "AAAAAA", "down": "False" }, { "name": "BBBBBB", ...

limitation on pairings of two generic types

How can I specify in TypeScript that "You can pass in any two objects, as long as their combination satisfies type X"? For example, consider the following function: function myFunction(options: {x: number, y: string}){ } Now, let's say we have anot ...

Encountering an Unexpected Token Error: Radium and React.js Inline Styles

Recently, I executed this command: npm install radium The installation was successful and I can confirm Radium is now present in my node modules folder. Reviewing my package.json file, I observed multiple dependencies including Radium. Could there be a ...

Javascript code has been implemented to save changes and address resizing problems

Code Snippet: <script> function showMe(){ document.querySelector('#change').style.display = ''; document.querySelector('#keep').style.display = 'none' document.querySelector('#change1').style.d ...

Retrieve the text from the outer span excluding any text from the inner elements

I am looking to retrieve specific text from an HTML element using Selenium and Javascript. <span class="myAttribute"> <b>SomeValueToIgnore</b> <span class="ignoreWhatsInside"> <em>ignore_that</em> </span& ...

From turning strings into integers to numerical transformations

I need help converting the string "9876543210223023" into an integer without changing its value. I've tried using parseInt, but it always converts to 9876543210223024 which is causing issues with my validations. Can someone suggest a method to keep th ...

Issue with Fancybox's close button not being displayed when using a different template

On one of my pages, I'm trying to use two different FancyBox styles for different elements. To accomplish this, I have included the tpl option and made adjustments to the stylesheet. Here is what I currently have: $(document).ready(function() { $(".l ...

What is the best way to transfer an array from an Express Server to an AJAX response?

My AJAX request successfully communicates with the server and receives a response that looks like this: [{name: 'example1'}, {name: 'example2'}] The issue arises when the response is passed to the client-side JavaScript code - it is t ...

Utilizing Radio Buttons for Table Selection in a React Application

Currently, I am utilizing React, MUI, and Formik in my project. My task involves implementing a table where only one radio button can be selected per row. How can I achieve this functionality? If you want to take a look at my code, it's available on ...

Unable to scroll to top using div scrollTop() function

Here's the fiddle I mentioned: http://jsfiddle.net/TLkmK/ <div class="test" style="height:100px;width:70px;overflow:auto"> Some text here that needs scrolling. </div> alert($('.test').scrollTop()); Feel free to scroll down ...

Generating interactive forms in Angular 7 using API data

I have developed a component that generates dynamic forms using angular reactive forms. When I attempt to utilize this component to create form fields in another component based on the response from my API, the form appears disabled and I am unable to make ...