Having trouble getting the Angular2 [innerHtml] directive to render properly?

Is there a way to inject HTML code from one Angular component into another using Angular 2 tags?

@Component({
  selector: 'app-root',
  template: '<app-a [my-html]="my-html"> </app-a>',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  my-html= '<span> {{variableFromAComponent}}</span>';
}



@Component({
      selector: 'app-a',
      template: '<div [innerHtml]="my-html"> </div>',
    })
    export class AComponent {
      @Input('my-html') my-html:any;
      public variableFromAComponent='its work!'; 
    }

Despite setting up the components in this way, the expected result of "its work!" is not displayed due to the angular2 tags preventing the variable from rendering properly.

Answer №1

I discovered a resolution by utilizing the angular2-dynamic-component library

<template dynamic-component
           [componentContext]="self"
           [componentModules]="dynamicExtraModules"
           [componentTemplate]='"here html tags with angular2 tags"'>
</template>

Answer №2

When using [innerHTML]="..." in Angular, the HTML added is not processed by Angular at all. It is simply added as-is. In some cases, you may need to use a Sanitizer to ensure that nothing is stripped for security reasons, as discussed in this post on Stack Overflow: In RC.1 some styles can't be added using binding syntax.

To dynamically add components in Angular, you can utilize

ViewContainerRef.createComponent()
. This allows you to create components based on user input or interactions, as demonstrated in this post on Stack Overflow: Angular 2 dynamic tabs with user-click chosen components

Answer №3

If you're looking to establish communication between components, there are a few approaches you can take.

COMPONENT INTERACTION

For components with a parent/child relationship, utilizing Input() and Output() decorators can facilitate the exchange of data.

The child component accesses the value via the Input(),

child.component.ts

import { Component, Input } from '@angular/core';
@Component({
  selector: 'child',
  template: '<div>{{myInfo}}</div>',
  providers: [ DataService]
})
export class ChildComponent implements OnInit {
   @Input() myInfo: string;
}

which is passed down from the parent component in the template:

parent.component.html

<child [myInfo]="'Your Text Here (or a variable containing "its work")'"></child>

To enable communication from child to parent, you can utilize Output().

SERVICES

Another method involves creating a shared service that is injected into both components. One component can transmit a value to the service, while the other can access that value. In Angular2, this can be achieved by employing observables for data propagation.

Answer №4

If you want to manipulate DOM elements in Angular, the Renderer2 Class is a useful tool.

import { ElementRef, Renderer2 } from '@angular/core';

constructor (
  private elementRef: ElementRef,
  private renderer: Renderer
) {}

public ngAfterViewInit(): void {
  this.renderer
     .setElementProperty(
        this.elementRef.nativeElement, 
        'innerHTML',
        '<h1> Custom Title </h1>'
     );
}

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

Function in Typescript that accepts an array or a single instance of a constructor and then returns a list

UPDATE:: reproducible link to the TypeScript playground I have also found a solution in the provided link, but I am still open to learning why my initial approach didn't work. TLDR; This method does not yield the expected results getEntitiesByComp ...

What is the best way to attach events to buttons using typescript?

Where should I attach events to buttons, input fields, etc.? I want to keep as much JS/jQuery separate from my view as possible. Currently, this is how I approach it: In my view: @Scripts.Render("~/Scripts/Application/Currency/CurrencyExchangeRateCreate ...

How to Send JS Type of 'Number' as an HTTP Response in Angular

I am currently developing an application using the MEAN stack (Mongo, Express, Angular, Node). In order to fetch the total number of entries in a collection, I am looking to create a GET route in Express that utilizes Mongo's countDocuments() method. ...

Concealing Bootstrap Dialog in Angular 6 through Component隐藏Angular 6中

I have been struggling to hide a bootstrap dialog from a component with no success. Here is my Dialog code: <div class="modal fade" id="loading_video_upload" tabindex="-1" role="dialog" aria-labelledby="loading_video_upload_label" aria-hidde ...

What is the best way to transform the data stored in Observable<any> into a string using typescript?

Hey there, I'm just starting out with Angular and TypeScript. I want to get the value of an Observable as a string. How can this be achieved? The BmxComponent file export class BmxComponent { asyncString = this.httpService.getDataBmx(); curr ...

Guide on moving elements to a different list with the help of the Angular DragDrop CDK Service

I encountered a unique situation while working on my project where I needed to implement a drag and drop feature for multiple lists using Angular CDK's DragDrop service. While I was able to successfully move items within a single list, transferring an ...

Guide to setting up a trigger/alert to activate every 5 minutes using Angular

limitExceed(params: any) { params.forEach((data: any) => { if (data.humidity === 100) { this.createNotification('warning', data.sensor, false); } else if (data.humidity >= 67 && data.humidity <= 99.99) { ...

When set to synchronize:true in Typeorm, any changes to an entity will result in the many-to

As a newcomer to typeorm, I've encountered a peculiar issue with the synchronize: true setting in my ormconfig.js. Whenever I make changes to an entity with a Many-to-Many relationship, any data present in the join table prior to the entity modificati ...

Creating a versatile TypeScript Record that can accommodate multiple data types

I have a question regarding the use of Record in TypeScript. When I specify Record as the parameter type in a function, I encounter an error in my code because it does not allow different types. type Keys = 'name' | 'qty'; const getVal ...

ngModel shows the same values for distinct fields

Currently working on an Angular 5 and Firestore project, where I have implemented a form using [(ngModel)] to update a document in the database. The update operation is successful, however, there seems to be an issue with how the [(ngModel)] is displaying ...

Implementing child components in React using TypeScript and passing them as props

Is it possible to append content to a parent component in React by passing it through props? For example: function MyComponent(props: IMyProps) { return ( {<props.parent>}{myStuff}{</props.parent>} } Would it be feasible to use the new compone ...

Tips on how to incorporate a .js file into my .tsx file

I ran into an issue with webpack displaying the following message: ERROR in ./app/app.tsx (4,25): error TS2307: Cannot find module './sample-data'. The imports in my code are as follows: import * as React from 'react'; import * ...

Combining switch statements from various classes

Is there a way to merge switch statements from two different classes, both with the same function name, into one without manually overriding the function or copying and pasting code? Class A: protected casesHandler(): void { switch (case){ ...

When an abstract method is invoked within the constructor of an abstract class, it does not have access to properties of

This code snippet is supposed to display 'Hello World!' on the screen, but instead it shows an error message: Error: Cannot read property 'id' of undefined. What could be the reason behind this issue? abstract class Parent { construc ...

Why is it that the HttpClient constructor in Angular doesn't require parameters when instantiated through the constructor of another class, but does when instantiated via the 'new' keyword?

I am trying to create a static method for instantiating an object of a class, but I have encountered a problem. import { HttpClient } from '@angular/common/http'; export MyClass { // Case 1 public static init(): MyClass { return this(new ...

The POST requests on Next JS Mock API endpoints include parameters passed in the req.body

I am currently running Next JS API tests using jest with a custom testClient. The code for the testClient is as follows: import { createServer } from 'http'; import type { NextApiHandler } from 'next'; import type { __ApiPreviewProps } ...

Angular component with @Input() directive allows data to be passed into

I am curious about how the @Input property's rendering works internally. In Angular, if I create a component with type and title as @Input properties, how does the component know that the value of the type property should be treated as a string, whil ...

Ensure that you only run `npm publish` in the Angular monorepo if there

In my angular monorepo, I have an "app" and a library that is published as its own npm package. The publishing process is automated on a CI environment. Previously, the library and app had separate build jobs. Now that they are built together, I am encount ...

Angular throws an error when attempting to use localStorage as it is not defined in the environment

Encountering an issue while running this code, as the error message "localStorage is not defined" keeps popping up. Additionally, when it comes to todos != Todo[], why can't we simply set it to null instead of using the exclamation mark? import { Comp ...

creating a JSON array within a function

I am currently developing an Angular application and working on a component with the following method: createPath(node, currentPath = []){ if(node.parent !==null) { return createPath(node.parent, [node.data.name, ...currentPath]) } else { retu ...