Fixing ngModel and click functionality issues in dynamic HTML content within Angular 4

I am struggling to insert HTML content into a specific id by using Angular. Although the HTML displays, the functionality of ngModel and click event is not working. How do I resolve this issue?

app.component.html

<div id="myid">

</div>

app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {

   mytext = "insert text here"
   constructor(private myElement: ElementRef) {}
   ngOnInit() {
    this.insertDiv()
  }
  showAlert(){
   alert("Hello")
  }
  insertDiv(){
    var div = document.createElement('div');
    div.innerHTML = `<div>
          <input type="text" [(ngModel)]="mytext">
           <button type="button" class="btn (click)="showAlert()">Click Me</button>
        </div>`;
    this.myElement.nativeElement.querySelector('#myid').append(div)
  }
}

Answer №1

CornelC brings up a valid point about the importance of good coding practices. In my own experience, I've utilized reactive forms and form arrays in similar scenarios. For more information on setting up a reactive form with a form array, check out this helpful answer:

How to dynamically add and remove form fields in Angular 2

Additionally, it's worth noting that the class attribute should be closed with a closing quote and the template string should also have a closing ` at the end:

div.innerHTML = `<div>
      <input type="text" [(ngModel)]="mytext">
       <button type="button" class="btn (click)="pop()">Basic</button>
    </div>;

To correct this, update the code snippet as follows:

div.innerHTML = `<div>
      <input type="text" [(ngModel)]="mytext">
       <button type="button" class="btn" (click)="pop()">Basic</button>
    </div>;`

Answer №2

If you dynamically create HTML and set it using innerHTML in Angular, you won't be able to use Angular-specific template syntax. Angular templates are compiled during build time, so things like (click)="..." will not work in this case.

It's generally recommended not to directly manipulate HTML when working with Angular.

To properly handle this scenario, consider creating your component as shown below:

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

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
    isDivVisible = false;
    mytext = 'add something';
    constructor(private myElement: ElementRef) { }
    ngOnInit() {
        this.isDivVisible = true;
    }
    pop() {
        alert('hello');
    }
}

Instead of manually creating DOM elements, use the isDivVisible variable to control visibility:

<div *ngIf="isDivVisible">
    <input type="text" [(ngModel)]="mytext">
    <button type="button" class="btn" (click)="pop()">Basic</button>
</div>

The div with *ngIf directive will only be visible when isDivVisible is true. You can hide it by setting isDivVisible to false.

Remember, if you use ngOnInit method, make sure your component also implements the OnInit interface.

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

Guide to locating a particular node within an array of nested objects by utilizing the object

Dealing with an array of nested objects, the goal is to compare values with a flat array and update the property matchFound. If the parent's matchFound is true, then all its children should inherit this value. treeData = [{ field: 'make&a ...

Issues with Angular routing in Fuse administrator and user interfaces

I am encountering an issue with navigating routes for admin and user roles, where the user role has limitations compared to the admin role. <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.1/angular.min.js"></script> const ...

Issue with running Angular Application through docker-compose.yml file is stopping the execution

Below is the docker file I have created for my angular application: Dockerfile: # base image FROM node:10.16.0-alpine AS build-step # set working directory WORKDIR /app COPY package.json ./ RUN npm install COPY . . RUN npm run build FROM nginx:1.16.1-alp ...

How to dynamically style a NgBootstrap modal in Angular during runtime

One of the features of my application is the ability to swap themes at runtime. The primary component in my app is called BaseComponent, which is added to my AppComponent and includes a theme property. This theme property represents a class that is applie ...

Error message in VueJS TypeScript: Implicit declaration of type 'props' as 'any'

Currently, I am working with vue 2.6 and typescript 3.8.3. The issue arises when I attempt to apply a validator to a prop. I am encountering error message TS7006: Parameter 'props' implicitly has an 'any' type. Below is the ...

Clicking on a button to transfer items between pages (Ionic 2 + Angular 2)

I'm in the process of creating a recipe application and one feature I'd like to include is a shopping list page. On this page, users can click an "Add to Shopping List" button which will transfer the ingredients listed in a <ul> onto anothe ...

What is the best way to utilize Object.keys() for working with nested objects?

When working with nested objects, I am trying to access the properties using Object.keys() and forEach(). However, I am encountering an issue when attempting to access the nested keys filteringState[item][el]. Is there a specific way to write a function f ...

Angular CLI 8.2.2 experiencing issues with displaying Themify icons

I recently added Themify icons to my project using npm install --save @icon/themify-icons from https://www.npmjs.com/package/@icon/themify-icons. My method for inserting an image into the site is as follows: <img height="32" width="32" src="@icon/themi ...

Enhance the Component Props definition of TypeScript 2.5.2 by creating a separate definition file for it

I recently downloaded a NPM package known as react-bootstrap-table along with its type definitions. Here is the link to react-bootstrap-table on NPM And here is the link to the type definitions However, I encountered an issue where the types are outdate ...

Reacting to the surprise of TS/JS async function behaving differently than anticipated

It appears that I'm facing a challenge with the small method; not sure if my brain is refusing to cooperate or what's going on. async fetchContacts() { await this.http.get('http://localhost:3000/contacts') .subscribe(res =& ...

What is the best way to transition this endpoint from JavaScript to TypeScript?

I'm in the process of building a chat application with the t3 stack. I've successfully created a socket endpoint using JavaScript, but now I'm facing some challenges as I try to convert it to TypeScript. import { Server } from "Socket.I ...

Encountering issues while trying to incorporate a trading chart library into an Angular 7 project

ERROR in src/assets/datafeeds/udf/src/udf-compatible-datafeed-base.ts(243,74): error TS2339: 'errmsg' Property Not Found The property 'errmsg' does not exist on the type 'UdfErrorResponse | UdfSearchSymbolsResponse'. The p ...

Divide a given number of elements within an array of arrays

Presented below is an array: [ { "id": "34285952", "labs": [ { "id": "13399-17", "location": "Gambia", "edge": ["5062-4058-8562-294 ...

What is the best way to initialize elements once the data has finished loading?

I am currently working with a service class that retrieves data through HTTP in several methods. For example: filesPerWeek(login: string): Observable<FilesLastActivity[]> { return this.http.get('api/report/user_files_by_week?userId=' + ...

Creating a custom date selection component in Angular 2 RC1

Can anyone recommend a datepicker that is compatible with Angular 2 RC1? I noticed that ng2-datepicker seems to be using angular2 RC1, but when trying to install it, it's asking for Angular 2 Beta. Would appreciate any assistance. Thank you in advan ...

What is the best way to incorporate an AJAX GET request into an HTML element?

Currently, I am attempting to execute a JavaScript code that will convert all <a></a> elements found within another element <b></b> (the specific name in the HTML) into links that trigger an HTTP get request. However, the code I hav ...

Assigning styles and values to an object using ngStyle

Within my component, I am encountering an issue where I am trying to edit some styles on a different component. I am passing an object to the component through property binding. The problem arises when updating the BorderRadius - it works when declaring a ...

Subscribe to the service in Angular and make repeated calls within the subscription

What is the most effective way to chain subscriptions in order to wait for a result before starting another one? I am looking for something similar to async/await in Javascript, where I need the result of the first call to trigger the next one. Currently, ...

Integrating concealed elements into jspdf

I am currently working on incorporating a hidden div into my jspdf file. Utilizing html2canvas for this purpose, I find it necessary to briefly make the div visible, add it to the pdf, and then hide it again. This method is not ideal as the content moment ...

Screen a roster for shared elements with another roster

Within my dataset, I am working with a List of Objects that adhere to the following Model structure: export class Animal{ public aniId: number; public aniName: string; } export Class Zoo{ public id: number; public name:string; public aniId: number ...