Issue
Following this tutorial I've created a reusable modal component. The modal itself is shown from other components (with an error ERROR TypeError: ctx_r1.modalConfig is undefined
), but I couldn't personalize it, i.e. it is an empty box, behaving like a modal.
Modal component is structured as follow:
Modal component
modal.component.html
modal.component.ts
modal.config.ts
where .config.ts looks like:
export interface ModalConfig {
modalTitle: string;
...
}
Here is component B, where I want to open a personalized modal:
b.ts file:
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>
If I try to assign some value to modaConfig, then the empty modal is not shown anymore and I get a new similar error:
ERROR Error: Uncaught (in promise): TypeError: _this.modalConfig is undefined
Does any one know what is the problem and how can I solve it?
Solution
We can change the config to a class, so that it can be used as a
Type
as well as initializing the initial values, then you can add more properties if needed to!
Could you change the interface to a class
export class ModalConfig {
modalTitle: string;
constructor(modalTitle = '') {
this.modalTitle = modalTitle;
}
}
Then you can change b.com.ts
to
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()
}
}
Answered By - Naren Murali
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.