What is the process for passing input values to a dynamic Angular component?

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

My goal is to develop a dynamic filtering system where users can specify multiple attributes and their corresponding values to filter a list of components. The dynamically added component includes two dropdown menus: one for attribute selection and another for attribute values. There is also an 'Add' button to add the next attribute filter component. The attribute list is filtered based on a selected catalog passed through an @Input. Here's how the pieces of this puzzle come together:

In the parent HTML document, the attribute filter container is included:

<app-attribute-filter-container [catalogSelected]="catalog"></app-attribute-filter-container>

The current setup of the attribute filter container involves an ng-template with a dynamic placeholder:

<ng-template #dynamic></ng-template>

Below is the TypeScript code for the container:

import { Component, NgModule, Inject, OnInit, ViewChild, ViewContainerRef, Input } from '@angular/core';
import { AttributeFilterCreatorService } from '../../services/attribute-filter-creator.service';
import { Catalog } from '../../interfaces/interfaces';

@Component({
  selector: 'app-attribute-filter-container',
  templateUrl: './attribute-filter-container.component.html',
  styleUrls: ['./attribute-filter-container.component.css'],
  providers: [AttributeFilterCreatorService]
})

export class AttributeFilterContainerComponent {
  @Input() catalogSelected: Catalog;
  service: AttributeFilterCreatorService;

  @ViewChild('dynamic', {
    read: ViewContainerRef
  }) viewContainerRef: ViewContainerRef

  constructor(@Inject(AttributeFilterCreatorService) service) {
    this.service = service;
  }

  ngOnInit() {
    console.log('Container Catalog: ', this.catalogSelected);
    this.service.setRootViewContainerRef(this.viewContainerRef);
    this.service.addDynamicComponent();
  }

}

Lastly, here is the TypeScript code for the attribute filter component:

import { Component, OnInit, ViewEncapsulation, Input, Inject } from '@angular/core';
import { Attribute, AttributeValue, Catalog } from '../../interfaces/interfaces';
import { HttpClient, HttpHeaders, HttpRequest, HttpEventType } from '@angular/common/http';
import { Router } from '@angular/router';
import { AuthService } from '../../services/auth.service';

@Component({
  selector: 'app-attribute-filter',
  templateUrl: './attribute-filter.component.html',
  styleUrls: ['./attribute-filter.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class AttributeFilterComponent implements OnInit {
  @Input() catalogSelected: Catalog;
  @Input() attributes: Attribute[];
  attributeValues: AttributeValue[];
  urlBase: string = "";
  selectedAttribute: Attribute;

  constructor(private auth: AuthService, private http: HttpClient, private router: Router, @Inject('BASE_URL') baseUrl: string) {
    this.urlBase = baseUrl;
  }

  ngOnInit() {
    if (!this.attributes) {
      this.LoadAttributes();
    }
  }

  attributeSelect(selectedAttribute) {
    this.LoadAttributeValues(selectedAttribute.id);
  }

  private LoadAttributes() {
    var attUrl = this.urlBase + 'api/Attribute/Attributes/' + this.catalogSelected.catalogcode;

    console.log("LOAD ATTRIBUTES", attUrl);

    this.http.get<Attribute[]>(attUrl).subscribe(result => {
      if (result.length == 0) {
        this.auth.logout();
        this.router.navigate(["login"]);
      }
      else {
        this.attributes = result;
      }

    }, error => console.error(error));
  }

  private LoadAttributeValues(attributeid) {
    this.attributeValues = [];

    var attValUrl = this.urlBase + 'api/Attribute/AttributeValues/' + this.catalogSelected.catalogcode + '/' + attributeid;

    this.http.get<AttributeValue[]>(attValUrl).subscribe(result => {
      if (result.length == 0) {
        this.auth.logout();
        this.router.navigate(["login"]);
      }
      else {
        this.attributeValues = result;
      }

    }, error => console.error(error));
  }

}

The value of catalogSelected does not get passed to the dynamically injected component, causing the attribute dropdown values not to load.

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

Teach Typescript to recognize a specific union type within a React component

Imagine I have an object of type: type BulkItem = { id: number; type: 'bulk'; tonnage: number } type RegularItem = { id: number; type: 'regular'; weight: number } export type CartItem = BulkItem | RegularItem // there could be more item ...

Unable to integrate the leaflet-realtime plugin with Angular5 and Ionic at this time

Having trouble utilizing the leaflet-realtime plugin in my Ionic3 & Angular 5 project When I import import leaflet from 'leaflet'; in this manner Upon attempting to implement real-time functionality with the following code snippet leaflet ...

The 'append' property is not present in the 'Headers' type in Angular 2

import { HttpClient, HttpHeaders } from '@angular/common/http'; export class LoginService { let headers: HttpHeaders = new HttpHeaders(); headers = headers.set('Content-Type', 'application/json'); } I encounter ...

How can I extend a third-party JavaScript library in TypeScript using a declaration file?

Currently, I am working on creating a .d.ts file for an external library called nodejs-driver. While I have been able to map functions and objects successfully, I am struggling with incorporating the "inherit from objects defined in the JS library" conce ...

What are the advantages of utilizing @input and @output instead of subject/services?

When passing data between child and parent components in Angular, we often utilize @Input and @Output. What advantages do @Input and @Output offer over using subjects or services? Aside from being the most conventional method provided by Angular itself, is ...

What is the best way to switch on/off data loading from the server with a click

I have a button with a click event that sends a server request each time it is clicked. The request should only be sent when the condition showVersions is true. The functionality of the button historyBtn should act as a toggle. This has been my attempt: ...

Having trouble with vscode compiling the typescript file?

Even though I diligently followed the tutorial provided by vscode on compiling typescript code, I encountered a problem. The configurations were set up as per the instructions in the tutorial, but when I tried to run the code without debugging, I received ...

Retrieve all the items listed in the markdown file under specific headings

Below is an example of a markdown file: # Test ## First List * Hello World * Lorem Ipsum * Foo ## Second List - Item 1 ## Third List + Item A Part of Item A + Item B ## Not a List Blah blah blah ## Empty ## Another List Blah blah blah * ITEM # ...

Exploring Angular2 utilizing matrix-style URL notation

Which is the preferred method for creating URLs with parameters - using matrix url notation or the traditional ? and & format? I found the explanation in the angular.io documentation confusing. localhost:3000/heroes;id=15;foo=foo or localhost:3000/h ...

Which is the better choice for simply invoking a service method - subscribe or toPromise?

When implementing the search method below, I simply assign the value of BehaviourSubject in the service. However, I am unsure whether it is possible to execute this operation without using either subscribe() or toPromise() after the .pipe() block in the ...

Showing the outcome of the request from the backend on an HTML page using the MEAN stack

I am currently in the process of developing an angular application with a node.js + express backend. After successfully retrieving the necessary data from MongoDB and being able to view it through terminal, I encountered a challenge when trying to display ...

Is it possible to modify the host header within an Angular app?

I'm experiencing a vulnerability issue and to resolve it, I need to utilize SERVER_NAME instead of the Host header. Is it possible to accomplish this using Angular? ...

Angular 2 - Component Loading Screen

I'm looking for a solution for my loading component that shows a spinner and retrieves a remote configuration file necessary for the app to work. Is there a way to have all routes pass through the loading component first to ensure the config data is l ...

The positioning of the button was off-kilter in Firefox

app.component.html: <div class="input-group col-12 d-flex align-items-baseline pb-3"> <p class="mb-0 pb-3 col-12">Verify....</p> <input type="url" class="form-control" id="validationC ...

The `@ViewChild` reference cannot be found

My main challenge is toggling a @ViewChild element using an *ngIf, followed by invoking a native event. This snippet shows my HTML element, tagged with #audioPlayer for extracting it through @ViewChild. <audio #audioPlayer *ngIf="convers ...

Having difficulty grasping the significance of the data received from the API response

Currently, as I am working on my personal Portfolio for a Web Developer course, I have encountered an issue with correctly implementing my API to retrieve information from the database. Previously, I faced no problem when using a .json file, but now, I am ...

Tips on effectively utilizing Chart.js with Typescript to avoid encountering any assignable errors

I'm encountering an issue while utilizing the Chart.js library in my Angular application with Typescript. The error message I'm receiving is as follows: Error: Object literal may only specify known properties, and 'stepSize' does not e ...

What is the best way to design a personalized legend in ng2-charts with full customizable options such as click functions and color schemes in Angular

In my current project involving Angular 4 and Ionic 3, I am using ng2 pie charts to display multiple data arrays. However, when the data in an array increases, the legend width also increases causing the chart to disappear because of the large data volume. ...

What is the best way to ensure that multiple queries are returned in the correct sequence?

In the interface below, there is a search input box along with data displayed. As you type in the search input, the data below filters accordingly. Each letter typed triggers a request to retrieve the relevant data. For instance, if you type "folder," the ...

Using Node.js: Only bring in the necessary function, don't execute the entire file

Today, I stumbled upon an interesting observation and I'm curious about the peculiar behavior of node in this scenario. I have two files structured as follows: src/api/index-api.ts src/worker/index-worker.ts Both of these files contain a simple con ...