首页 > 解决方案 > Angular 不将“模态”识别为元素

问题描述

我使用 Angular 从我的项目中创建了一个组件;一切正常,直到我添加一个窗口,现在当我为我的应用程序提供服务并且 Angular 说“模态不是已知元素”时什么都没有出现。

HTML 文档

<modal>
<div class="modal">
  <div class="modal-body">
      <h1>A Custom Modal!</h1>
      <p>
          Home page text: <input type="text" />
      </p>
      <button (click)="closeModal('custom-modal-1');">Close</button>
   </div>
</div>
<div class="modal-background"></div>
</modal>

模态组件文件:

 import { Component, OnInit, ElementRef, Input, OnDestroy } from 
    '@angular/core';
        import {ModalWindowService} from './modal-window.service';

       @Component({
        selector: 'app-modal-window',
      templateUrl: './modal-window.component.html',
       styleUrls: ['./modal-window.component.css']
       })

       export class ModalWindowComponent implements OnInit {
     @Input() id: string;
     private element: any;

         constructor(private modalService: ModalWindowService, private el: 
  ElementRef) {
  this.element = el.nativeElement;
   }

  ngOnInit(): void {
  let modal = this;

  // ensure id attribute exists
  if (!this.id) {
      console.error('modal must have an id');
      return;
       }

    // move element to bottom of page (just before </body>) so it can be 
     displayed above everything else
     document.body.appendChild(this.element);

   // close modal on background click
    this.element.addEventListener('click', function (e: any) {
      if (e.target.className === 'modal') {
          modal.close();
      }
     });

       // add self (this modal instance) to the modal service so it's 
    accessible from controllers
  this.modalService.add(this);
   }

        // remove self from modal service when directive is destroyed
          ngOnDestroy(): void {
     this.modalService.remove(this.id);
      this.element.remove();
     }

       // open modal
        open(): void {
     this.element.style.display = 'block';
       document.body.classList.add('modal-open');
           }

        // close modal
       close(): void {
         this.element.style.display = 'none';
        document.body.classList.remove('modal-open');
       }
     }

我将 HTML 文件用于“模板”,而不是在组件内使用它。我已经在我的模块中声明了该组件。

标签: javascripthtmlangulartypescriptmodal-dialog

解决方案


您的选择器名称是app-modal-window

<app-modal-window>
<div class="modal">
  <div class="modal-body">
      <h1>A Custom Modal!</h1>
      <p>
          Home page text: <input type="text" />
      </p>
      <button (click)="closeModal('custom-modal-1');">Close</button>
   </div>
</div>
<div class="modal-background"></div>
</app-modal-window>

如果您想像这样<modal>更改选择器一样使用它

   @Component({
    selector: 'modal',
  templateUrl: './modal-window.component.html',
   styleUrls: ['./modal-window.component.css']
   })

推荐阅读