Encountering an undefined value in Typescript

I am facing an issue that I can't seem to resolve.

I would like the 'dialogTitle' variable to display the startHour and startMinute variables along with the title variable. However, I keep getting the title and 'undefined' repeated after the title. What steps should I take?

event-form.component.ts

import { Component, Inject, ViewEncapsulation } from '@angular/core';
import { FormBuilder, FormControl, FormGroup } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material';

import { MatColors } from '@fuse/mat-colors';

import { CalendarEvent } from 'angular-calendar';
import { CalendarEventModel } from '../event.model';

import { locale as eventFormEnglish } from './i18n/en';
import { locale as eventFormDutch } from './i18n/nl';

import { FuseCalendarComponent } from '../calendar.component';

@Component({
    selector     : 'fuse-calendar-event-form-dialog',
    templateUrl  : './event-form.component.html',
    styleUrls    : ['./event-form.component.scss'],
    encapsulation: ViewEncapsulation.None
})

export class FuseCalendarEventFormDialogComponent
{
    event: CalendarEvent;
    dialogTitle: string;
    eventForm: FormGroup;
    action: string;
    startHour: string;
    startMinute: string;
    endHour: string;
    endMinute: string;
    presetColors = MatColors.presets;

    //Shows dropdown items

    startTimeHours = [
        {value: 'time-0', viewValue: '7'},
        {value: 'time-1', viewValue: '8'},
        {value: 'time-2', viewValue: '9'},
        {value: 'time-3', viewValue: '10'},
        {value: 'time-4', viewValue: '11'},
        {value: 'time-5', viewValue: '12'},
        {value: 'time-6', viewValue: '13'},
        {value: 'time-7', viewValue: '14'},
        {value: 'time-8', viewValue: '15'},
        {value: 'time-9', viewValue: '16'},
        {value: 'time-10', viewValue: '17'},
        {value: 'time-11', viewValue: '18'},
        {value: 'time-12', viewValue: '19'},
        {value: 'time-13', viewValue: '20'},
        {value: 'time-14', viewValue: '21'},
        {value: 'time-15', viewValue: '22'},
        {value: 'time-16', viewValue: '23'}
    ];
    // More code...

event-form.component.html

<div class="dialog-content-wrapper">
    <mat-toolbar matDialogTitle class="mat-accent m-0">
        <div fxFlex fxLayout="row" fxLayoutAlign="space-between center">
            <span class="title dialog-title">{{dialogTitle}}</span>
            <button mat-button class="mat-icon-button"
                    (click)="dialogRef.close()"
                    aria-label="Close dialog">
                <mat-icon>close</mat-icon>
            </button>
        </div>
    </mat-toolbar>

    <div mat-dialog-content class="p-24 m-0" fusePerfectScrollbar>

        <form name="eventForm" [formGroup]="eventForm" class="event-form w-100-p" fxLayout="column" fxFlex>

            <mat-form-field class="w-100-p">
                <input matInput
                       name="title"
                       formControlName="title"
                       [placeholder]="'FORM.TITLE' | translate"
                       required>
            </mat-form-field>

            <div class="py-16" fxFlex="1 0 auto" fxLayout="row">
              <!-- More HTML code -->
            </div>
          
            <div fxFlex="1 0 auto" fxLayout="column" fxLayout.gt-xs="row">
              <!-- More HTML code -->
            </div>

            <mat-form-field formGroupName="meta" class="w-100-p">
                <input matInput
                       name="location"
                       formControlName="location"
                       [placeholder]="'FORM.LOCATION' | translate">
            </mat-form-field>

            <mat-form-field formGroupName="meta" class="w-100-p">
                <textarea matInput
                          formControlName="notes"
                          [placeholder]="'FORM.NOTES' | translate"
                          mat-maxlength="250"
                          max-rows="4">
                </textarea>
            </mat-form-field>

        </form>

    </div>

    <div mat-dialog-actions class="m-0 p-16" fxLayout="row" fxLayoutAlign="space-between center">
        <!-- More HTML code -->
    </div>
</div>

It appears that the issue might be related to how the two variables are being declared or accessed. It could also be a matter of order in the code. Have you considered checking the database entries for the startHour and startMinute variables? They are expected to be fetched from the database but need to be handled properly. The database is referenced in another file:

calendar.component.ts

// Code related to calendar functionality

If you require further assistance or clarification, feel free to ask! Thank you.

Answer №1

It seems that you have not assigned any values to the variables startHour or startMinute. In the section where you have specified their types as string:

startHour: string
startMinute: string

You are only declaring their types without providing a value. If you wish to assign a value, you can do so at the same point by initializing them like this:

startHour: string = 'value'
startMinute: string = 'value'

Alternatively, you can assign values in the constructor before using them:

this.event = data.event;
this.action = data.action;

this.startHour = 'value';
this.startMinute = 'value';

if ( this.action === 'edit' ) {
  this.dialogTitle = this.event.title + " - " + this.startHour + ":" + this.startMinute;
}

I hope this explanation is helpful and wish you good luck!

Answer №2

Distinction Between Declaration and Definition

designation: string; // The act of specifying a variable without assigning a value.
console.log(this.designation); // Will output undefined.

designation: string = '';  // Both specifying and assigning a value to the variable.
console.log(this.designation); // Will output an empty string.

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

Connecting the outcome of a Promise with an Observable

Forgive me if this is a silly question. I searched high and low but couldn't find the answer I need. I'm trying to figure out how to pass the value for index, which is returned in the Promise, as an argument to my Observable: deleteFavorite(tok ...

Having some issues with ng-hide in angular, it doesn't seem to be functioning properly

<nav class="menu-nav"> <ul> <li class="menu-li" ng-model="myVar"><a>Discover<i class="fa fa-chevron-down pull-right"></i></a> <div class="sub-menu" ng-hide="myVar"&g ...

JavaScript array sorting not functioning for specialized logic

I am facing an issue with sorting arrays. I have a custom logic for displaying the array where each object has a 'code' column with values ('A', 'B', or 'C'). The requirement is to sort the records to display 'B ...

Reverse row changes in Angular Ag-Grid with the click of a button

Developed using Angular and JavaScript technologies. The AG-Grid consists of editable records with the first column being a checkbox. When changes are made to any selected records, clicking on a particular record's checkbox and then pressing a button ...

Combining two objects by aligning their keys in JavaScript

I have two simple objects that look like this. var obj1 = { "data": { "Category": "OUTFLOWS", "Opening": 3213.11, "Mar16": 3213.12, "Apr16": 3148.13, "May16": 3148.14, "Jun16" ...

I am currently facing challenges retrieving data from a post request in my Angular/Typescript frontend application connected to an ASP.NET backend

I am currently working on a web application that relies on backend processing. To communicate between my Angular(v14)/Typescript front end and an ASP.NET backend, I am sending a post request. Backend Code [HttpPost] public async Task<string> Process ...

Struggling to understand how to properly 'map' my data from the response in Next.js 13 using Typescript

Just a few days into my journey with next.js, and I'm already facing a challenge in figuring out how to fetch data from an API. In regular React, I would typically use useState and useEffect for managing state and fetching data. But when it comes to n ...

Creating a new Angular library with SASS using Angular CLI

I'm currently working on an Angular6 app where I need to create a library. However, after generating the library project, I noticed that Angular CLI is automatically creating components with .css files instead of .scss files. Is there any way I can f ...

Customizable Styled Templates with Dynamic Async Pipe Parameters

I'm trying to transition my code to a more Reactive style, but I'm having trouble with the syntax when passing parameters through the async pipe to an Observable. Here's my current working code that isn't Reactive (student.component.ts ...

I am struggling to grasp the concept of ref unwrapping within a TypeScript template

I'm currently in the process of converting some Vue3 code from javascript to typescript, and I am struggling to comprehend the unwrapping of a ref/computed value in the template. I used to believe that the template would automatically unwrap reactiv ...

Convert a Java library to JavaScript using JSweet and integrate it into an Angular project

Just recently, I embarked on my journey to learn TypeScript. To challenge my newfound knowledge, I was tasked with transpiling a Java library using JSweet in order to integrate it into an Angular project. This specific Java library is self-contained, consi ...

Guide to Setting Up "Remember Me" Login for Users in Angular

I am having trouble setting the 'Remember Me' option on my Login page. I tried using localstorage session but it seems like something is missing in the service file that's causing it not to respond properly. I attempted to follow a guide on ...

Converting array elements to strings in Python - A guide

I am facing a challenge with an array called myArray that contains 4 elements. myArray = [myFunc(), "Pears", myFunc(), "Pears"] My goal is to convert the function call of myFunc() into a string format, such as "myFunc()" Th ...

Securing API keys in an Angular 2 client-side application: Best practices

Currently, I am working on an Angular 2 project and facing the challenge of making API calls from my service without exposing the keys. While it is recommended to use keys from the backend, I wonder if there is a secure way to handle this directly from th ...

Angular 2 GET request returns a 404 error

I have been attempting to reproduce the ngPrime datatable demo from this Github repository. Currently, I am working with the most recent version of Angular (4) and using angular-cli in development mode. Placing a JSON file into my app folder where the serv ...

Executing a function on a converted TypeScript object

My experience with using Cloud Firestore has been smooth in casting to an object, but I have encountered an issue when trying to call methods on that object. Below is the model definition I am working with - contact.ts export class Contact { id: string ...

Guide to configuring a custom "page not found" error page in Spring Boot 2 and Angular

In the previous version of Spring Boot <2, I used to implement the following: @Configuration public class MvcConfig extends WebMvcConfigurerAdapter { @Override public void addViewControllers(ViewControllerRegistry registry) { registry. ...

"Omitting the parameter value when passing it to a directive in Angular

I recently developed a Directive in Angular7, but I encountered an issue when trying to pass a string value from the HTML to the directive. When using the following code snippet in my HTML: <ng-template [appValidatePermission]='CreateRole'&g ...

What is the best way to work with the INITIAL_STATE injection token when it has dependencies

I have a dynamic module that loads lazily and uses ngrx/store with the feature StoreModule.forFeature('tasks', tasksReducer). To initialize this module, I need to set some initial values that are obtained through dependency injection from another ...

The map() function's splice operation unexpectedly removes only half of the array

I am currently working with an array that contains 146 objects, each object having its own unique id. My goal is to delete any objects from the array that do not have a matching id. I wrote a function to accomplish this task, however, it only works for hal ...