Search code examples
angularmodal-dialogcomponentsdaisyui

Angular reusable Modal component binding id and for attribute issue


I have configured dynamic modal but click out of modal to close won't works because input id and for attribute are binded from parent component.

Stackblitz example

@Component({
  selector: 'app-modal',
  standalone: true,
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [],
  template: `
    <input
      type="checkbox"
      [id]="id()"
      class="modal-toggle"
      [checked]="open()"
    />
    <div class="modal" role="dialog">
      <div class="modal-box">
        <ng-content></ng-content>
      </div>
      <label class="modal-backdrop" [attr.for]="id()">Close</label>
    </div>
  `,
  styles: ``,
})
export class ModalComponent {
  id = input<string>('appmodal');
  open = input<boolean>(false);
}

Solution

  • The problem is that by naming your component's input id, there is a name collision with the native id property. Angular tries to do its best with it and treats it both as an input and as an attribute which is added to the DOM. As a result, now there are two elements with the same ID in the DOM, on the app-modal element and on the checkbox. Because the modal element is the first element in the DOM, it has precedence. For this reason the modal closing mechanism stops working. Just rename the input to something else than id which makes the ID unique again, and it works.

    Updated StackBlitz