按照本教程,我创建了一个可重用的模态组件。模态本身是从其他组件中显示的(有错误ERROR TypeError: ctx_r1.modalConfig is undefined
),但我无法对其进行个性化,即它是一个空框,表现得像模态。模态组件的结构如下:
Modal component
modal.component.html
modal.component.ts
modal.config.ts
.config.ts 看起来像:
export interface ModalConfig {
modalTitle: string;
...
}
这是组件B,我想在其中打开个性化模态:b.ts 文件:
import { Component, Injectable, Input, OnInit, TemplateRef, ViewChild } from '@angular/core'
import { ModalConfig } from '@app/.../modal/modal.config';
import { ModalComponent } from '@app/.../modal/modal.component';
@Component({
selector: 'b',
templateUrl: './b.component.html',
standalone: true,
imports: [ ModalComponent ]
})
export class BComponent {
public modalConfig!: ModalConfig;
@ViewChild('deleteConfirmModal') private modalComponent!: ModalComponent;
async openModal() {
this.modalConfig.modalTitle = "Confirm your action";
return await this.modalComponent.open()
}
}
b.html
<modal #deleteConfirmModal [modalConfig]="modalConfig"> </modal>
如果我尝试为 modaConfig 分配一些值,则不再显示空模态,并且我收到一个新的类似错误:
ERROR Error: Uncaught (in promise): TypeError: _this.modalConfig is undefined
有人知道问题是什么以及如何解决吗?
我们可以将配置更改为一个类,这样它就可以用作你能把接口改成类吗
Type
以及初始化初始值,然后您可以根据需要添加更多属性!
export class ModalConfig {
modalTitle: string;
constructor(modalTitle = '') {
this.modalTitle = modalTitle;
}
}
然后您可以将 b.com.ts
更改为
import { Component, Injectable, Input, OnInit, TemplateRef, ViewChild } from '@angular/core'
import { ModalConfig } from '@app/.../modal/modal.config';
import { ModalComponent } from '@app/.../modal/modal.component';
@Component({
selector: 'b',
templateUrl: './b.component.html',
standalone: true,
imports: [ ModalComponent ]
})
export class BComponent {
public modalConfig!: ModalConfig = new ModalConfig(); // I've also tried @Input() public modalConfig!: ModalConfig;
@ViewChild('deleteConfirmModal') private modalComponent!: ModalComponent;
async openModal() {
this.modalConfig.modalTitle = "Confirm your action"; // adding this, the error changes and the modal is not shown anymore
return await this.modalComponent.open()
}
}