javascript - 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 文件用于“模板”,而不是在组件内使用它。我已经在我的模块中声明了该组件。
解决方案
您的选择器名称是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']
})
推荐阅读
- r - 框架(动画)不考虑更新菜单选择的参数
- material-ui - 材质表滚动条样式
- javascript - jQuery在加载时显示特定宽度的隐藏圆形文本何时应该隐藏
- docker - Docker for Windows - IPv4 端口意外关闭,IPv6 端口不受影响
- r - R:如何根据特定情况将值从一个数据帧传输到另一个数据帧?
- c# - Xamarin iOS 下的 Hi-jack NSLog
- python - 重命名 Fastapi/Pydantic json 输出字段
- python - 在python中将32位二进制转换为十进制
- scala - sbt 未观察到包名
- python - 如何使用 django 在另一个模型中创建元素