3

In my Angular project I have a select-box component, which get datas from my data models. Options coming from basically a service, the selected value coming from the current opened data model.

I want to implement an add button near the select tag. If the user clicks on this button, he get a modal window with a form for the model what is shown in the select. If the user add here a new instance of model, the data will be saved to storage and select will be updated with this new instance.

I use complicated forms with many select fields - coming with many plus buttons, opens many create components.

I want to avoid to render these component until the user clicks to the given plus button.

Here is my parent component's TypeScript code:

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  // this coming from a data service
  langs = [
    {id: 1, name: 'english'},
    {id: 2, name: 'deutsch'},
    {id: 3, name: 'latin'},
  ];

  // coming from a data service
  model = {
    id: 100,
    name: 'John Doe',
    lang_id: 3,
  }
}

Here is an example how I use right now my select component:

<app-select-box [items]="langs" [selectedValue]="model.lang_id">
  <app-lang-create-edit></app-lang-create-edit>
</app-select-box>

Here is my select-box component's HTML code:

<div class="input-group">
  <select class="form-control">
      <ng-container *ngFor="let item of items">
        <option [value]="item[value]">{{ item.names[0][text] }}</option>
      </ng-container>
  </select>
  <div class="input-group-append" *ngIf="!buttonHide">
    <button class="btn btn-light" tabindex="-1" (click)="showModal(modal)"> + </button>
  </div>
</div>

<!-- Modal -->
<div class="modal" tabindex="-1" role="dialog" *ngIf="isModalOpen">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
      <h5 class="modal-title">Add new element</h5>
      <button type="button" class="close" (click)="hideModal()">
          <span aria-hidden="true">&times;</span>
      </button>
      </div>
      <div class="modal-body">
          <ng-content></ng-content>
      </div>
    </div>
  </div>
</div>

I think the problem is coming from usage of the ng-content tag, because it's render the incoming code at same time when the <div class="modal" ...> is rendering.

Here is the working example with more detailed codes.

Can I avoid somehow to render the app-lang-create-edit component until the modal isn't visible?

I want to rerender every time if the user close and reopen the modal dialog.

Is there any solution?

netdjw
  • 5,419
  • 21
  • 88
  • 162

0 Answers0