Angular: Generating components dynamically in HTML is unsuccessful

I possess the capability to dynamically generate components:

import { Component, ComponentFactory, ComponentFactoryResolver, ComponentRef, OnInit, ViewChild, ViewContainerRef } from '@angular/core';
import { FilterComponent } from '../filter/filter.component';

export enum FilterType {
  DateRangeFilter, SensorSelectFilter
}

@Component({
  selector: 'app-filter-collection',
  templateUrl: './filter-collection.component.html',
  styleUrls: ['./filter-collection.component.css']
})
export class FilterCollectionComponent implements OnInit {

  filters: Array<ComponentRef<FilterComponent>> = [];

  @ViewChild("messagecontainer", { read: ViewContainerRef }) entry!: ViewContainerRef;

  constructor(private resolver: ComponentFactoryResolver) { }

  onAddDateRangeFilter() {
    const factory: ComponentFactory<FilterComponent> = this.resolver.resolveComponentFactory(FilterComponent);
    const filter = this.entry.createComponent<FilterComponent>(factory);
    filter.instance.filter = FilterType.DateRangeFilter;
    this.filters.push(filter);
  }

  onAddSensorSelectFilter() {
    const factory: ComponentFactory<FilterComponent> = this.resolver.resolveComponentFactory(FilterComponent);
    const filter = this.entry.createComponent<FilterComponent>(factory);
    filter.instance.filter = FilterType.SensorSelectFilter;
    this.filters.push(filter);
  }

  ngOnInit(): void {
  }

}

whereas FilterComponent is structured as follows:

@Component({
  selector: 'app-filter',
  templateUrl: './filter.component.html',
  styleUrls: ['./filter.component.css']
})
export class FilterComponent {

  @Input() filter!: FilterType;

  _FilterType = FilterType;

  range = new FormGroup({
    start: new FormControl(),
    end: new FormControl()
  });

  constructor() {
  }

  ngOnInit(): void {

  }

}

with the following HTML structure:

<div *ngIf="filter === _FilterType.SensorSelectFilter">
<mat-form-field class="sensorFilter" appearance="fill">
    <mat-label>Cars</mat-label>
    <select matNativeControl required>
        <option value="volvo">Volvo</option>
        <option value="saab">Saab</option>
        <option value="mercedes">Mercedes</option>
        <option value="audi">Audi</option>
    </select>
</mat-form-field>
</div>
<div *ngIf="filter === _FilterType.DateRangeFilter">
<mat-form-field class="dateFilter" appearance="fill">
    <mat-label>Enter a date range to filter data</mat-label>
    <mat-date-range-input [formGroup]="range" [rangePicker]="picker">
        <input matStartDate formControlName="start" placeholder="Start date">
        <input matEndDate formControlName="end" placeholder="End date">
    </mat-date-range-input>
    <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
    <mat-date-range-picker #picker></mat-date-range-picker>

    <mat-error *ngIf="range.controls.start.hasError('matStartDateInvalid')">Invalid start date</mat-error>
    <mat-error *ngIf="range.controls.end.hasError('matEndDateInvalid')">Invalid end date</mat-error>
</mat-form-field>
</div>

Still, I am encountering difficulties in rendering these components in HTML. I tried including the following code snippet in FilterCollectionComponent.html:

<div *ngFor="let filter of filters">
    <app-filter [filter]="filter.instance.filter"></app-filter>
</div>

Yet, this approach seems to be ineffective.

Any insights on why this method is not working properly? Your assistance is highly appreciated!

Answer №1

filter-collection.component.html:

<div #dynamicFilters></div>

filter-collection.component.ts

import { Component, ComponentFactory, ComponentFactoryResolver, ComponentRef, OnInit, ViewChild, ViewContainerRef } from '@angular/core';
import { FilterComponent } from '../filter/filter.component';

export enum FilterType {
  RangeFilter, SelectionFilter
}

@Component({
  selector: 'app-filter-collection',
  templateUrl: './filter-collection.component.html',
  styleUrls: ['./filter-collection.component.css']
})
export class FilterCollectionComponent implements OnInit {

  filters : Array<ComponentRef<FilterComponent>> = [];

  @ViewChild('dynamicFilters', { read: ViewContainerRef }) dynamicInsert!: ViewContainerRef;

  constructor(private resolver: ComponentFactoryResolver) { }

  onAddRangeFilter() {
    const factory: ComponentFactory<FilterComponent> = this.resolver.resolveComponentFactory(FilterComponent);
    const filter = this.dynamicInsert.createComponent<FilterComponent>(factory);
    filter.instance.filter = FilterType.RangeFilter;
    this.filters.push(filter);
  }

  onSelectSelectionFilter() {
    const factory: ComponentFactory<FilterComponent> = this.resolver.resolveComponentFactory(FilterComponent);
    const filter = this.dynamicInsert.createComponent<FilterComponent>(factory);
    filter.instance.filter = FilterType.SelectionFilter;
    this.filters.push(filter);
  }

  ngOnInit(): void {

  }

}

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

How to create an editable dropdown feature in HTML with Angular 10

Currently, I am using Angular and I am looking for a way to create an editable dropdown in HTML with the help of Angular. Can anyone provide a code snippet for this? ...

What is causing the IE CSS fix to fail in Internet Explorer 8? The IE statement does not seem to end properly

Greetings! I recently attempted to implement an IE fix on my website, however, it seems that it is not effective for IE8. Should I provide more specific instructions? <!--[if IE]> <link rel="stylesheet" type="text/css" href="/AEBP_Homepage_12 ...

I am working on a project where I have a parent component that contains a textarea element. My goal is to dynamically adjust the height of this textarea

Is there a way to adjust the size of a textarea component in a child component? textarea.html <textarea style = "height"=150px></textarea> // The height is defined globally here xyz.html <app-textarea></app-textarea> // Looking ...

Enhance your webpage with a stunning background video

I'm trying to add a background video that covers the entire screen but maintains a height of 400px, similar to the one shown here. Is there a way to achieve this without using JavaScript? Below is the HTML code I currently have: <div class="pr ...

Support for ViewEncapsulation.ShadowDom now available in Edge, Internet Explorer, and legacy browsers

I am working with Angular 7 and material design. Some of my components utilize ShadowDOM ViewEncapsulation, leading to errors in older versions of IE, Edge, Chrome, and Firefox. Below is the error message I am encountering: Object doesn't support pr ...

What crucial element is absent from my array.map function?

I have successfully implemented a table with v-for in my code (snippet provided). However, I am now trying to use Array.map to map one array to another. My goal is to display colors instead of numbers in the first column labeled as networkTeam.source. I at ...

Text not aligning properly when utilizing the <p> tag

I'm struggling to align my text in a row, as shown below: https://i.sstatic.net/SGQ8I.png "Investup" and "Real estate" should be aligned. I need to move the "Real estate" paragraph so that it aligns with the "invest up" paragraph. Here's my co ...

Setting up Emotion js in a React TypeScript project using Vite 4

Currently, I am in the process of transitioning from Webpack to Vite for my React Typescript application. I have been attempting to integrate Emotion js into the project. "@vitejs/plugin-react": "^4.0.1", "vite": "^4.3.9 ...

Discovering Typescript: Inferring the type of a union containing specific strings

I am working with a specific type called IPermissionAction which includes options like 'update', 'delete', 'create', and 'read'. type IPermissionAction = 'update' | 'delete' | 'create' | ...

Issue with fading hover effect on links is not functioning

I recently implemented a fade link hover effect using the code snippet below: a:link {color:#333333; text-decoration: none; -o-transition:.5s; -ms-transition:.5s; -moz-transition:.5s; -webkit-transition:.5s; transition:.5s;} a:visited {color:#FF0033; ...

Discovered two instances of duplicate IDs within the elements

When using the same id names in two different form tags, I am encountering the following warnings: [DOM] Found 2 elements with non-unique id Below is a portion of my HTML code: <div class="modal-dialog"> <form action="" ...

What is the best way to emphasize a table row during a search rather than just the text?

I am currently using a jQuery script that searches for a specific string in a simple text input field and highlights only the string itself if it is found. However, my data is organized within a table and I am interested in knowing if it is possible to hig ...

The smooth scrolling feature is not functioning properly as the links are jumping to the top and bottom instead of scrolling

My links are supposed to smoothly scroll to the bottom and top, but they're not working correctly even though I believe the JavaScript is functioning properly. Here is the JavaScript code: $.fn.ready(function() { // Smooth scroll to top ...

When the script is placed at the end of the file, document.getElementById() is still returning null

I need assistance with running a JavaScript function that is located at the end of my .aspx file. This is the div tag in question: <div id="div_NRContainer" oninit="div_NRContainer_Init" class="panelContainer" runat="server"> Following this, with ...

Quiz application features various button states for optimal user interaction

I am in the process of creating a quiz that resembles the popular BuzzFeed quizzes such as THIS ONE. Although I have mapped out the logic and have an idea of how to code it to function similarly to the one provided in the link, I am encountering issues wit ...

"Continue to shine until the rendering function displays its source code

I've encountered a strange issue where I'm using lit until to wait for a promise to return the template, but instead of the desired output, the until's function code is being rendered. For example: render() { return html` <div c ...

Issue with ngfactory.js warning in Angular 6+ when building in production mode, but the development build is running without any

I am encountering an error while trying to build Angular for production. Can someone please provide a solution to this issue? WARNING in ./src/app/userforms/login/login.component.ngfactory.js 149:679-708 "export 'MAT_PROGRESS_BAR_LOCATION' (impo ...

There seems to be a disconnect between the CSS and HTML files

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>JavaScript Basics</title> <link rel="stylesheet" href="style.css"> </head> <body> <div class="c ...

Tips for positioning Material Ui buttons beside a list of images

I have a list of images and I would like to display buttons beneath each image Here is my current code: export const Media = (stuff) => { const { medias } = stuff; console.log(medias); const classes = useStyles(); return ( <div classNam ...

Stopping the sound when its' Div is hovered over

I've managed to successfully trigger the audio to play on hover, but I'm having trouble getting it to pause when my mouse leaves the area. Check out the code in action here: https://jsfiddle.net/jzhang172/nLm9bxnw/1/ $(document).ready(functio ...