Removing the id attribute in the innerHTML property of Angular 4

After making an API call to load HTML content into an element by updating the innerHTML, everything seems to be working fine except for one issue - the id attribute gets removed from the loaded content.

Here is the component code:

 content: string;
 @ViewChild('div') divContainer: ElementRef;

  constructor(private cd: ChangeDetectorRef) {
    // loading content using an API call
    setTimeout(() => {
      this.content = "<a href='#' id='cafeteria' class='cafeteria'>Cafeteria</a>";
      this.cd.detectChanges();  
      this.divContainer.nativeElement.querySelector('#cafeteria').addEventListener('click', (e) => {
        e.preventDefault();
        console.log('clicked');
      });
    }, 1000);
  }

Template:

 <div #div [innerHTML]="content"></div>

Upon inspecting in the Chrome console:

https://i.sstatic.net/c8x8l.png

In the code snippet above,

this.divContaainer.nativeElement.querySelector('#cafeteria')
returns null because the id is missing. However, when I replaced it with a class selector, it worked properly.

The loaded content lacks the id attribute but retains the class attribute. Is there a specific reason for this behavior?

Answer №1

give this a shot: http://plnkr.co/edit/JfG6qGdVEqbWxV6ax3BA?p=preview

implement a safeHtml filter using

.sanitized.bypassSecurityTrustHtml

@Pipe({ name: 'safeHtml'})
export class SafeHtmlPipe implements PipeTransform  {
  constructor(private sanitized: DomSanitizer) {}
  transform(value) {
    return this.sanitized.bypassSecurityTrustHtml(value);
  }
}

@Component({
  selector: 'my-app',
  template: `<div #div [innerHTML]="content | safeHtml"></div>1`,
})

Answer №2

When innerHtml isn't being used in multiple places

Within your TypeScript file

content = "<a href='#' id='cafeteria' class='cafeteria'>Cafeteria</a>";
newContent:any;

    constructor(private sanitized: DomSanitizer) { 
        this.newContent = this.sanitized.bypassSecurityTrustHtml(content)
    }

In your HTML file

<div #div [innerHTML]="newContent"></div>

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

In TypeScript, use a Record<string, any> to convert to {name: string}

I have developed a custom react hook to handle API calls: const useFetch: (string) => Record<string, any> | null = (path: string) => { const [data, setData] = useState<Record<string, any> | null>(null); var requestOptions: Requ ...

AngularJS controller experiencing scope() function returning undefined issue

I've been working with a function inside the controller: $scope.passValues = function (param1){ return "foo"; }; console.log($scope.passValues()); It logs foo, but then I tried this: $scope.passValues = function (param1){ return param1; ...

How can a callback be properly passed in programming?

My coding approach is outlined below: var CustomLibrary = (function (window, $, undefined) { return { URI: 'http://testpage/API/', OnSuccess: function (data, status) { }, OnError: function (request, status, error) { } ...

Error: Material-UI prop type validation failed. Please specify either children, image, src, or component prop for CardMedia component. This error occurred at

I encountered an issue while trying to utilize the CardMedia component from Material-ui. The error message received was 'Failed prop type: Material-UI: Either children, image, src, or component prop must be specified. at CardMedia'. I attempted v ...

Non-functioning function within object

this is a unique object var Manager = (function () { var self = this; self.fetch = function (request, response) { response.send({ message: 'Data fetched successfully' }); } return self; })() module.ex ...

The property 'enabled' is not a standard feature of the 'Node' type

Within the code snippet below, we have a definition for a type called Node: export type Node<T> = T extends ITreeNode ? T : never; export interface ITreeNode extends TreeNodeBase<ITreeNode> { enabled: boolean; } export abstract class Tre ...

In Node.js Express, the download window won't pop up unless the entire file has been sent in the header response

I have been using Express to develop an API that allows users to download PDF files. The download process is functioning correctly, but I am facing an issue where the download window, which prompts me to select a destination folder for the download, only a ...

Inject the code snippet from CodePen into a WordPress webpage

I have a WordPress page where I want to integrate the HTML, CSS and JS code from my Codepen project. The styling appears to be working correctly, but the JavaScript is not functioning as expected. You can view the page here: Could someone assist me in pr ...

Error: The fetch API encountered an unexpected termination before completing the request

A new issue has come up in my project, and although I found a similar problem on this link, it does not address my specific issue. What I have set up is a straightforward API using nodejs, express-framework, and mongoose. The issue lies with the fetch API ...

Struggling to grasp the concept of nested scope within AngularJs

I found myself puzzled while reading an article on this particular website (pitfall #5): My query is: Does this situation resemble having two variables with the same name in plain JavaScript, where one is locally defined (e.g. within a nested function ...

Navigating through pages using Nuxt UI-pagination

Having some trouble with setting up the pagination feature from Nuxt UI. Despite trying to research through documentation and videos, I can't seem to figure out how to connect my data to the component. <template> <div> ...

The process of altering a span label's class with JavaScript

I am currently working with an HTML element that looks like this: <dd><span class="label label-success" id="status">Production</span></dd> My goal is to update it to: <dd><span class="label label-warning" id="status"> ...

What is the process for cancelling an interval when it is disabled in my configuration file?

To automate a bot, I want it to stop running an interval if the configuration file specifies "off" and continue running if it says "on". I attempted this: Using discord.js: config.Interval = setInterval(() => { WallCheck.send(WallCheckemb ...

When I decide to incorporate both BootstrapVue and Vuetify CSS frameworks into a single project

Can I incorporate two CSS frameworks into my current Nuxt.js project? Does anyone have any insight on why it might be beneficial to use two different CSS frameworks in a Vue.js project? Please provide some guidance on this matter. I am looking to optimize ...

Chrome browser is experiencing an issue with the Modal RadWindow not closing properly

In my main "Report" page, there are actions available to the user that open a modal RadWindow. The user can then take actions within the modal window, click Save, and the modal window should close while the main grid refreshes. While this functionality wo ...

Iterating through a JSON query in AngularJS using the ng-repeat directive

Using AngularJS in my current project has been a smooth experience so far. One thing I have noticed is that when I loop over employees in my view, I have to use the code <li ng-repeat="employee in employees.employee"> instead of just <li ng-re ...

TS Mapped Type: Dynamically exclude specific keys based on their values

Seeking a method to create a mapped type that excludes specific keys based on the value of the mapped key. For instance: Consider an option: Options struct, where Options is a union type defined as: { type: DataType } or { type: DataType, params: DataPar ...

Is there a bug in Safari 8.0 related to jQuery and backslashes?

I am using Mac OS 10.10 Yosemite and Safari 8.0. Attempting to read an XML (RSS) file: <content:encoded>bla bla bla</content:encoded> The Javascript Ajax method I am using is: description:$(valeur).find('content\\:encoded&apo ...

What could be causing my Ionic/Firebase subscription to be triggered three times?

I'm having an issue with my code where it seems to be executed 3 times and I can't figure out why. advertenciaMantto() { this.afs.doc('Core/Programador').valueChanges().subscribe(async (data) => { await this.afs.firestore.doc(` ...

We are currently moving up from NG 12 to NG 16 and encountering an issue with the package "@ng-bootstrap/ng-bootstrap" due to an incompatible peer dependency

When attempting to upgrade from Angular version 12 to version 13, we encountered some dependency errors. Following the instructions at https://update.angular.io/?v=12.0-13.0, we tried running ng update @angular/core@13 @angular/cli@13. We received the fo ...