我使用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文件用于“模板”,而不是在组件内部使用它。我已经在模块中声明了该组件。
答案 0 :(得分:1)
您的选择器名称是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']
})