Adding HTML content to a container in Angular 2 using TypeScript

My goal is to add some HTML content to an element. After researching various solutions online, I came across many confusing and ineffective methods.

To achieve this using JavaScript, I can use the following code:

var d1 = document.getElementsByClassName('one');
d1.insertAdjacentHTML('beforeend', '<div class="two">two</div>');

Is there a way to accomplish the same task using typescript/angular2, specifically with RC5?

EDIT

The element with class .one is generated by an external JS script that cannot be modified.

Answer №1

1.

<div class="first" [innerHtml]="htmlToAdd"></div>
this.htmlToAdd = '<div class="second">two</div>';

Check out In RC.1 some styles can't be added using binding syntax

  1. Alternatively
<div class="first" #one></div>
@ViewChild('one') d1:ElementRef;

ngAfterViewInit() {
  d1.nativeElement.insertAdjacentHTML('beforeend', '<div class="second">two</div>');
}

or to avoid direct DOM manipulation:

constructor(private renderer:Renderer) {}

@ViewChild('one') d1:ElementRef;

ngAfterViewInit() {
  this.renderer.invokeElementMethod(this.d1.nativeElement', 'insertAdjacentHTML' ['beforeend', '<div class="second">two</div>']);
}
    3.
constructor(private elementRef:ElementRef) {}

ngAfterViewInit() {
  var d1 = this.elementRef.nativeElement.querySelector('.first');
  d1.insertAdjacentHTML('beforeend', '<div class="second">two</div>');
}

Answer №2

Introducing the latest feature in Angular - the powerful Renderer2

constructor(private renderer:Renderer2) {}

  @ViewChild('one', { static: false }) d1: ElementRef;

  ngAfterViewInit() {
    const d2 = this.renderer.createElement('div');
    const text = this.renderer.createText('two');
    this.renderer.appendChild(d2, text);
    this.renderer.appendChild(this.d1.nativeElement, d2);
  }

Answer №3

Here is an example of how you can achieve this:

customComponent.ts

htmlContent: string = "<h3>Some custom content.</h3>";
//This code contains HTML that needs to be rendered in TypeScript

customComponent.html

<div [innerHTML]="htmlContent"></div>
//This is how you display the HTML content from TypeScript in your template

Answer №4

Discover a more Angular-focused approach for a superior solution.

  1. Store your string in a variable within the .ts file

    MyStrings = ["one","two","three"]

  2. Incorporate *ngFor in the HTML file.

    <div class="one" *ngFor="let string of MyStrings; let i = index">
         <div class="two">{{string}}</div>
     </div>

  3. If you wish to dynamically add the div element, simply append more strings to the MyStrings array

    myFunction(nextString){
        this.MyString.push(nextString)
     }

By clicking the button containing the myFunction(nextString), you are essentially adding another class="two" div, replicating the action of inserting it into the DOM using pure javascript.

Answer №5

Angular 8 has brought a recent update that requires a static property to be included inside the @ViewChild() method, as mentioned in this link and here. In order to implement this change, you need to adjust your code like so:

@ViewChild('one') d1:ElementRef;

transform it into

// query results available in ngOnInit
@ViewChild('one', {static: true}) foo: ElementRef;

OR

// query results available in ngAfterViewInit
@ViewChild('one', {static: false}) foo: ElementRef;

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

Name or Title of a Polygon/Polyhedron Using Three.js

My page contains a sample code that successfully retrieves the name of an object when a user clicks on it. However, the code works well with cubes and spheres but fails with polygons. To see how the clicks respond, you can check the console logs. What shou ...

What is the best way to retrieve strings from an asynchronous POST request?

I am currently working on implementing a signup function in my Angular app using a controller and a factory. However, I am facing an issue where the strings (associated with success or failure) are not being returned from the factory to the controller as e ...

When is the best time to assign properties to mobx domain objects?

When it comes to tackling a specific problem in my react/mobx application, I'm facing challenges finding an optimal solution. Imagine having multiple boxes that need to be positioned on the screen based on various factors such as interdependency betwe ...

Dealing with unexpected modifications in a React class component

In short, I need to adjust the data in my class component before sending it to the server to match the API request format. To achieve this, I created a method called transformData within my class component which transforms the data extracted from the state ...

Executing the stop button in the browser with Webdriver IO

Just a bit of background: The program I'm testing is located within another website that requires login credentials. Once logged in, I can access the screen I need to test by typing in the direct link. However, there's an issue where my automated ...

Failure to load dependencies for deprecated Angular2 router

After updating my Angular2 version, I encountered an issue that the router lib no longer exists and has been replaced by router-deprecated. The menu component I have is as follows: import { Component } from '@angular/core'; import { Da ...

Typescript: Verifying the type of an interface

In my code, I have a function called getUniqueId that can handle two different types of interfaces: ReadOnlyInfo and EditInfo. Depending on the type passed to this function, it will return a uniqueId from either interface: interface ReadOnlyInfo { item ...

I'm looking for some good .NET MVC frameworks that can help create dynamic AJAX applications

I am interested in developing applications with a dynamic user interface that utilizes ajax technology. Some key features I am looking for include: Automatic saving of user input in forms, even if the data is incomplete Realtime validation of form fields ...

Decide on the chosen option within the select tag

Is there a way to pre-select an option in a combobox and have the ability to change the selection using TypeScript? I only have two options: "yes" or "no", and I would like to determine which one is selected by default. EDIT : This combobox is for allow ...

Ensuring your app is compatible with older versions of Node.js: A guide

Is there a way to develop a Node.JS application using the latest features of JS and Node.JS (like Node.JS v8 or even v13) and deploy it on an embedded Linux server with Node.JS v4 (Omega2, OpenWRT, MIPS arch)? I am looking for solutions or suggestions on ...

Determining the best use-case for a React framework like Next or Gatsby versus opting for Create React App

As I delve into the world of React and JavaScript, I find myself in the fast-paced prototyping stage. I can't help but ponder at what point developers choose to utilize frameworks like Next.js or Gatsby.js over the usual Create React App. I'm pa ...

What is the best way to retrieve the IDs of selected items in jQuery selectables?

I have a straightforward question that I've been struggling to find an answer to. When using jQuery selectables, I want to retrieve the ID of the selected list item when it's clicked. Here is an example of my list: <ol id="selectable"> ...

Unable to update state in my React app when clicking on a button

There is a requirement for a button click to filter the job-card array by one specific category. For example, clicking on the button "Marketing" should only show jobs from the array that have the property "jobstags: Marketing". I followed a similar procedu ...

Unable to view the refreshed DOM within the specifications after it has been altered

For my current project, I am working on writing a functional spec that involves using Mocha/JSDOM and making assertions with 'chai'. The specific use case I am tackling is related to the function called updateContent: When this function is exec ...

Executing mocha using Typescript results in a TypeError [ERR_UNKNOWN_FILE_EXTENSION] because the file extension ".ts" is unrecognized

I've been experimenting with Typescript and Mocha to write some tests. After following the documentation, I've set up the following: package.json { //... "scripts": { "test": "mocha", }, //... } .mocharc.j ...

Error caused by the shouldDisableDate prop in MUI DatePicker's functionality

<Controller name="toDate" control={control} defaultValue={null} render={({ field }) => ( <DatePicker format="DD/MM/yyyy" value={field.value} onChange={(e) => { setToDate(e); field.onC ...

Generate Angular component unit tests that involve manipulating the DOM using TypeScript

Currently, I am in the process of developing a UI library in Angular 16. While creating a component like a textarea in my typescript file, I find that manipulating the DOM element at a logical level works smoothly. However, when attempting to write tests, ...

Using node.js to import functions from another file

The code below is what I currently have: // app.js var exports = module.exports = {}; module.exports = function () { var exported = {}; .. exported.myFunction = function (data, callback) { .. } . ...

Determine the height of a DIV element and its contents using JQuery

In this div, there are various elements present: <div class="menuItem designMenu" id="dMenu"> <ul class="menuList menu"> <li class="menuHeader">Design</li> <li class="projectHeader">Mother</li> <li clas ...

JSON.stringify doesn't support circular structures in Loopback and mongodb, resulting in a TypeError

I have been working on implementing a remote method for loopback and have encountered an issue. "use strict"; module.exports = function(Quote) { /** * * @param {Function(Error, object)} callback */ Quote.random = function(callback) { ...