How can I implement a dynamic form to display only when there are values available for the specified ID?

https://i.stack.imgur.com/imqYb.pngI am dealing with an object that is coming from the backend, containing template parameters such as "namespace,resources". In some cases, the template parameter value is "null". My goal is to display a form only when there are values in the template parameter "namespace,resources", and I do not want to display it when it's null. How can I achieve this? I have tried splitting the values but now I need help writing code that will only show the form if there are actual values present. I hope my question makes sense. Thank you for your assistance. Html:

<form [formGroup]="templateform">

    <div class="form-group">
        <label for="ntw-pol-egren-podns"  class="bmd-label-floating">{{variable1}}<sup
        class="text-danger">*</sup>
        </label>
        
        <input  [(ngModel)]="namespace" formControlName="namespace" type="text" class="form-control" id="ntw-pol-egren-podns">
        
        <div *ngIf="submitted && f.namespace.errors" class="error-feedback error">
            <p *ngIf="f.namespace.errors.required" class="text-danger">
                Namespace is required
            </p>
        </div>
    </div>
    
    <div class="form-group">
        <label for="ntw-pol-egren-podns" class="bmd-label-floating">{{variable2}}<sup
        class="text-danger">*</sup></label>
        
        <input type="text" class="form-control" formControlName="resource" [(ngModel)]="resources"  id="ntw-pol-egren-podns">
        <div *ngIf="submitted && f.resource.errors" class="error-feedback error">
            <p *ngIf="f.resource.errors.required" class="text-danger ">
                Resource is required
            </p>
        </div>
    </div>
    
    <div class="d-flex justify-content-end">
        <button  (click)="sendclusteridApi()"  class="btn btn-primary px-3 py-2">Save</button>
    </div>
</form>

ts:

changeSelection() {
    this.selectedItemsList = this.DisplayProductList.filter((product, index) => {
        this.selectedItemsList.push(this.DisplayProductList[index])
        console.log(this.selectedItemsList,"sel")
        let splitstring = this.DisplayProductList[index].template_parameter
        console.log(splitstring,"df")
        let separatedArray = splitstring.split(',');
        this.variable1 = separatedArray[0];
        this.variable2 = separatedArray[1];
        return product.isChecked;
    });
}

Answer №1

Generate Form Groups:

 productFG: FormGroup;

Loop through the array this.DisplayProductList and create a FormGroup for each entry

const productFArray = this.DisplayProductList.map(obj =>
  this.createFormGroup(obj)
);

this.productFG = this.fb.group({
  policies: this.fb.array(productFArray)
});

When creating a FormGroup, dynamically add controls for Id, label, and create a nested FormGroup named additionalParams for template_parameter

private createFormGroup(obj): FormGroup {
    return this.fb.group({
      id: [obj.id],
      label: [obj.label],
      additionalParams: this.formGroupByTemplate(obj.template_parameter)
    });
  }

  private formGroupByTemplate(template_parameter: string): FormGroup {
    const splitted = template_parameter.split(',');
    if (template_parameter == '') {
      return this.fb.group({});
    } else {
      const formGroup = this.fb.group({});
      splitted.forEach(val => formGroup.addControl(val, this.fb.control(null)));
      return formGroup;
    }
  }

Additional helper methods

  get policiesFormArray(): FormArray {
    return this.productFG.get('policies') as FormArray;
  }

  getGroup(index: number): FormGroup {
    return this.policiesFormArray.at(index) as FormGroup;
  }

  getTemplateFG(index: number): FormGroup {
    return this.getGroup(index).get('additionalParams') as FormGroup;
  }

  getFormGroupKeys(index): string[] {
    return Object.keys(this.getTemplateFG(index).controls);
  }

In the template: Utilize getFormGroupKeys to fetch the formControlName from the additionalParams FormGroup.

<form [formGroup]="productFG">
  <div formArrayName="policies">
    <div *ngFor="let control of policiesFormArray.controls; let i=index">
      <div [formGroupName]="i">
        <div> {{ "Id : "+ getGroup(i).get('id').value }} - {{ getGroup(i).get('label').value }} </div>
        <div formGroupName="additionalParams" *ngFor="let key of getFormGroupKeys(i);">
          {{ key }} : <input type="text" [formControlName]="key"><br><br>
        </div>
      </div>

    </div>
  </div>

</form>

Live Demo

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

Angular 5: Display a blank URL with the source until the variables are resolved

In my template, if I have: <img src="/somepath/{{user?.UserGuid}}.png" /> When user is not yet resolved, the ?. prevents evaluating UserGuid, resulting in: <img src="/somepath/.png" /> Is there a way to prevent this without using *ngIf or c ...

Tips for styling your Angular Material Card on mobile devices

Currently, I am very happy with my desktop layout which looks like this: https://i.stack.imgur.com/tG0pw.png However, when it comes to the mobile version of my site, here is what I have so far: https://i.stack.imgur.com/KD1hh.jpg While I do like the ho ...

It appears that the input variables in Angular (5) are experiencing some issues

After upgrading my Angular project from version 4 to 5, I've noticed some unexpected changes in the behavior of my components. In my application, there is a ParentComponent and a ChildComponent. The ChildComponent receives an InputObject from its par ...

Provider not found: ConnectionBackend – NullInjectorError

I encountered the following error while attempting to load the webpage. Despite trying various suggestions from other sources, I have been unable to find a solution. Below the error stack lies my code. core.js:7187 ERROR Error: Uncaught (in promise): Null ...

The @Input directive is not compatible with the OnPush change detection strategy

page.html <app-parcel-delivery-cost-promo [parcelDeliveryCost]="parcelDeliveryCost"> </app-parcel-delivery-cost-promo> page.ts changeDetection: ChangeDetectionStrategy.OnPush, parcelDeliveryCost: Partial<ParcelDeliveryCostModel>; ...

Is there a way to integrate a calendar feature within an Angular 2 application?

I am brand new to Angular 2 and have a question: I need to integrate a calendar into a page where users can add events. Something similar to the following example: I'm unsure if the angular material calendar project is designed for Angular 2 or for ...

Avoiding an event from spreading in Angular

I am working on a navigation setup that looks like this: <a (click)="onCustomParameters()"> <app-custom-start-card></app-custom-start-card> </a> When the user clicks on the app-custom-start-card, the onCustomParame ...

Tips on looping through a dynamic FormControl using Angular2 and FormBuilder

I am facing an issue when trying to iterate over a dynamically generated FormControl in the HTML section. Instead of displaying the expected values, I am getting [object Object],[object Object] in the input field. Here is the provided data structure: { ...

Angular: Enhancing URL links

Recently, I discovered a function in my code that allows me to cycle through different pictures and change the URL accordingly. The initial URL is obtained using angular routes, where the "domain" parameter consists of the domain.id and the domain.category ...

What is the proper way to set up @Input?

I attempted to accomplish this in the following manner: @Input() data: any[] = []; Upon entering the ngOnInit lifecycle method, I notice that this.data is undefined: ngOnInit() { console.log(this.data); } Consequently, when trying to access th ...

Updating an array within a dynamic form using patchValue in Angular 4

My dynamic form, inspired by the Angular documentation, includes a feature that allows users to load their saved forms. I have encountered an issue where I am able to patch the values of text fields and radio buttons successfully, but I am facing difficu ...

The Ng2AutoCompleteModule library, which contains the ng2-auto-complete module, was not correctly processed by ngcc or is not compatible with Angular Ivy

I am in the process of upgrading Angular from version 2 to 15 and encountering an error. Can anyone provide assistance with this issue? It seems that the ng2-auto-complete library, which declares Ng2AutoCompleteModule, has not been processed correctly by ...

Encountered issues with the BsModalService in displaying the modal functionality

I am encountering an issue while attempting to display a modal using a service. When I call the service from a button, everything works fine. However, I encounter an error when calling it from an error handler. TypeError: Cannot read property 'attach ...

The HttpPut request code format is malfunctioning, although it is effective for another request

I'm struggling with a HTTPPUT request that just won't get called. Strangely enough, I have a similar put request that works perfectly fine for another tab even though both pages are practically identical. I've exhausted all options and can&a ...

Issue with Angular 2: Not receiving events when subscribing to a service's Subject property

Presented below is a service: @Injectable() export class AuthService { public reset: Subject<any>; constructor() { this.reset = new Subject(); } public logout() { this.reset.next('logout'); } } Here is an additional s ...

Conceal the choice when aria-expand is in a deactivated state

I'm currently facing a challenge with hiding an option in mat-select only when aria-expanded is false. In the dropdown menu, I have both "Select All" and "Deselect All" options. However, when the menu is closed, it displays "Deselect All" by default ...

The Nx end-to-end Cypress runner ensures that values from the cypress.env.json file do not overwrite the same entries in the cypress.json environment object

Having encountered an issue with my Nx powered angular project, I am facing a situation where the values provided in a cypress.env.json file are not overriding the corresponding entries in the env object of the cypress.json configuration file. This is a n ...

Generating a fresh array based on the size of its existing elements is the key feature of the ForEach method

When running this forEach loop in the console, it extracts the property "monto_gasto" from an array of objects in the firebase database. Here's how it looks: something.subscribe(res => { this.ingresos = res; ...

Trigger the browser to refresh translation files following the deployment

Our Angular/Ionic app utilizes the ngx-translate/core package for translations, and is hosted on Firebase. With each new build and deployment, Angular automatically creates a hash for our js files to ensure the browser fetches the latest version when chang ...

Creating an Angular feature module with the aim of converting it into an Angular library

Currently, I am developing an angular feature module as a library to enable us to create individual modules without the need to rebuild the entire angular application. While this approach seems to be functioning well, my question is whether it is conside ...