javascript - "modal" känns inte igen av Angular som ett element
Jag skapade en komponent till mitt projekt med Angular; allt fungerade bra tills jag lade till ett fönster och nu visas ingenting när jag kör min app och Angular säger "modal är inte ett känt element".
HTML-dokument
<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>
Modal komponentfil:
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');
}
}
Jag använder en HTML-fil för "Template" istället för att använda den inne i komponenten. Jag har deklarerat den komponenten i mitt modul.
Svar #1
Ditt selektornamn är 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>
om du vill använda det som <modal> ändra markören så här
@Component({
selector: 'modal',
templateUrl: './modal-window.component.html',
styleUrls: ['./modal-window.component.css']
})
