A guide to accessing another component's config.ts file in Angular

After following the steps outlined in this tutorial, I successfully created a reusable modal component. However, when trying to personalize it, I encountered an issue where the modal appeared as an empty box and displayed the error

ERROR TypeError: ctx_r1.modalConfig is undefined
when called from other components.

The structure of the modal component is as follows:

Modal component
   modal.component.html
   modal.component.ts
   modal.config.ts

The contents of .config.ts file are as follows:

export interface ModalConfig {
    modalTitle: string;
...
}

Below is component B, where I attempted 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>

When trying to assign a value to modalConfig, the modal no longer appears and a similar error is thrown:

ERROR Error: Uncaught (in promise): TypeError: _this.modalConfig is undefined

If anyone has encountered this issue before and knows how to resolve it, your insights would be greatly appreciated.

Answer №1

Adjusting the configuration to a class allows for greater flexibility, as it can be utilized as a Type while also facilitating the initialization of initial values. Additional properties can also be added if required!

Is it possible to convert the interface into a class?

export class ModalConfig {
    modalTitle: string;
    
    constructor(modalTitle = '') {
       this.modalTitle  = modalTitle;
    }
}

Subsequently, the modifications in b.com.ts would be as follows:

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(); // @Input() public modalConfig!: ModalConfig; has also been attempted
    @ViewChild('deleteConfirmModal') private modalComponent!: ModalComponent;

    async openModal() {
        this.modalConfig.modalTitle = "Confirm your action"; // upon including this, the error changes and the modal ceases to appear
        return await this.modalComponent.open()
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to invoke a client-side function from the server?

Is there a way to display an alert at the top of the browser if the SQL query returns empty results? I tried using the "alert" function, but I'm struggling with customizing its appearance. I have a function in my HTML code that triggers an alert, but ...

Angular component failing to refresh data upon service response

Within my Angular component, I have integrated badges onto certain icons. These badge numbers are fetched from an api upon entering the page, utilizing ionViewWillEnter(). Once the api response is received, the outcome is stored in a local variable, which ...

Encountering an issue with compiling Angular due to a Type Inference error

interface Course { name: string; lessonCount: number; } interface Named { name: string; } let named: Named = { name: 'Placeholder Name' }; let course: Course = { name: 'Developing Apps with Angular', lessonCount: 15 }; named = ...

Achieving a shuffling CSS animation in Angular 8 may require some adjustments compared to Angular 2. Here's how you can make it

Seeking assistance with animating an app-transition-group component in Angular 8. My CSS includes: .flip-list-move { transition: transform 1s; } Despite calling the shuffle function, the animation always happens instantly and fails to animate properly ...

What are the best techniques for concentrating on a kendo maskedtextbox?

What is the correct way to set focus on the kendo-maskedtextbox in TypeScript after the view has initialized? The information provided in Telerik's example here is lacking in detail. ...

Using TypeScript and webpack, include the access_token in the http header when making requests with axios

I need to include an access_token in the header of axios, following this example: https://github.com/axios/axios#global-axios-defaults Currently, I am fetching the access_token using razor syntax, which is only accessible in CSHTML files. https://github ...

JSX tags without any inner content should be self-closed

After successfully running this code, I encountered an issue when committing it to git. The error message 'ERROR: src/layouts/index.tsx:25:9 - JSX elements with no children must be self-closing' appeared. I attempted to resolve the error by addi ...

The cross-origin resource sharing configuration has not been implemented

I have SenseNet 7.0.0 and ASP.NET 5.2.3 set up, with my Angular (Typescript) application running on localhost:4200 and the ASP.NET application running on localhost:55064. I followed this tutorial for installing Sensenet and used this tutorial for installin ...

What methods can be used to test included content in Angular?

When testing an Angular component that includes transclusion slots utilizing <ng-content>, it becomes challenging to verify if the transcluded content is correctly placed within the component. For instance: // base-button.component.ts @Component({ ...

Error: Prisma seed - encountering issues with undefined properties (unable to read 'findFirst')

I've encountered a strange issue when using prisma seed in my nextjs full-stack project that I can't seem to figure out. Normally, when running the app with `next dev`, everything works smoothly and the queries are executed without any problems. ...

Access the Angular directive instance before it is actually rendered

Is it possible to access an Angular directive instance even if it has not been rendered yet? Let's say I have an app-component and a baz-directive. I want to be able to get the directive instance even if it is not currently shown or rendered in the D ...

Merging the functions 'plainToClass' and 'validate' into a single generic function in NodeJs

Here's the issue I'm facing: export const RegisterUser = async (request: Request): Promise<[number, UserResponse | { message: any }]> => { let userRequest = plainToClass(UserRequest, request.body); let errors = await validate(u ...

Invalid Redux store: Element type is not valid; a string type is expected

I am running into an issue while setting up the redux store with typescript for the first time. The error message I am encountering is: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) ...

Discover a Simple Trick to Enhance tsc Output: Unveil the Art of

When I work on a TypeScript project, I typically use the watch mode of the compiler: tsc --watch However, one issue I face is that it's challenging to identify errors in the output since they are displayed as plain text: Sometimes I don't even ...

Leveraging Angular 2 directives in TypeScript to bind a value from a custom control to an HTML control

I have created a unique custom directive named "my-text-box", and within this directive, I am utilizing the HTML control <input>. I want to pass values from my custom control to the HTML input control. In Angular 1, I would simply do something like & ...

Enhance the design of MDX in Next.js with a personalized layout

For my Next.js website, I aim to incorporate MDX and TypeScript-React pages. The goal is to have MDX pages automatically rendered with a default layout (such as applied styles, headers, footers) for ease of use by non-technical users when adding new pages. ...

Guide on generating angular <popover-content> programmatically

My goal is to generate angular elements dynamically. While static creation works perfectly fine, I am facing challenges when trying to create them dynamically using data. For instance: <div> <popover-content #pop1 title=" ...

Troubleshooting Guide: Resolving the Error Message 'ControlContainerAngular' Provider Not Found in Your Angular App

Incorporating bootstrap-4 into my angular7 application for design purposes. <nav class="navbar navbar-light bg-light"> <form class="form-inline"> <div class="input-group"> <div class="inp ...

What is the proper way to implement ref in typescript?

Currently, I am in the process of learning how to use Vue3 + Typescript. Previously, I have developed Vue2 applications using plain JavaScript. In my current project, I am attempting to define a reactive variable within the setup() function: setup() { ...

Managing state within SolidJS components using Immer's "produce" for nested state handling

I've been working on a SolidJS application where I store a large JSON object with nested objects. For undo and redo actions, I'm using Immer to generate patches. Although technically I'm storing a class with multiple layers of nesting, Immer ...