Modifying Data with MomentJS when Saving to Different Variable

After attempting to assign a moment to a new variable, I noticed that the value changes on its own without any modification from my end.

Despite various attempts such as forcing the use of UTC and adjusting timezones, the value continues to change unexpectedly.

@Component({
  selector: 'app-appointment-create',
  templateUrl: './appointment-create.component.html',
  styleUrls: ['./appointment-create.component.css']
})
export class AppointmentCreateComponent implements OnInit {

  appointment: CreateAppointmentDto;
  form: FormGroup;
  private formSubmitted: boolean;
  tasks: Task[];
  availability: Availability[];
  task: number;
  availablemoments: Moment[];

  constructor(
    private titleService: Title,
    private router: Router,
    private appointmentService: AppointmentService,
    private taskService: TasksService,
    private webLogger: WebloggerService,
    private availabilityService: AvailabilityService,
  ) {
    this.appointment = new CreateAppointmentDto();
  }

  dateFilter = (d: Moment): boolean => {
    return this.availability.filter(s => s.timestampstart.isSame(d, 'day')).length >= 1;
  }

  ngOnInit() {
    this.titleService.setTitle('New Appointment');

    this.taskService.getActiveTasks().subscribe(value => {this.tasks = value; });

    this.form = new FormGroup({
      timestampstart: new FormControl(this.appointment.timestampstart, Validators.required),
      daystart: new FormControl(this.appointment.timestampstart, Validators.required),
      location: new FormControl(this.appointment.location, Validators.required),
      description: new FormControl(this.appointment.description, Validators.required),
      paid: new FormControl(false, Validators.required),
      serviceType: new FormControl(this.appointment.serviceTypeId, Validators.required),
      client: new FormControl(this.appointment.clientId, Validators.required),
      assignedUser: new FormControl(this.appointment.assignedUserId, Validators.required),
    });
  }

  onSubmit(event) {
    event.preventDefault();
    this.formSubmitted = true;

    if (this.form.valid) {
      this.form.disable();
      this.appointment.timestampstart = this.form.get('timestampstart').value;
      this.appointment.location = this.form.get('location').value;
      this.appointment.description = this.form.get('description').value;
      this.appointment.paid = this.form.get('paid').value;
      this.appointment.serviceTypeId = this.form.get('serviceType').value;
      this.appointment.clientId = this.form.get('client').value;
      this.appointment.assignedUserId = this.form.get('assignedUser').value;
      this.appointmentService.createNewAppointment(this.appointment)
        .subscribe(value => { this.router.navigate([`/dashboard/appointment/${value.id}/edit`]); });
    } else {
      this.webLogger.error('The form is invalid, please check the values');
    }
  }

  selectTask($event: Event) {
    this.task = Number(this.form.get('serviceType').value);
    this.availabilityService.getAvailabilityForTask(this.task).subscribe(value => {
      this.availability = value;
    });
  }

  setTime($event: Event) {
    this.availablemoments = [];
    const dayAvailability: Availability[] = this.availability.filter(
      s => s.timestampstart.isSame(moment(this.form.get('daystart').value), 'day'));
    const currentDate = dayAvailability.reduce((prev, curr) => prev.timestampstart < curr.timestampstart ? prev : curr).timestampstart;
    dayAvailability.forEach(value => {
      while (value.timestampend.isAfter(currentDate)) {
        if (!this.availablemoments.includes(moment(currentDate))) {
          this.availablemoments.push(moment(currentDate));
        }
        currentDate.add(30, 'minutes');
      }
    });
  }
}

The `availability` array consists of objects with start and end moments.

I anticipate that the output from the second console log should match the first console log.

UPDATE:

This is how the `Availability` class is structured:

export class Availability {
  id: number;
  timestampstart: Moment;
  timestampend: Moment;
  location: string;
  description: string;
  paid: boolean;
  payment: Invoice;
  serviceType: Task;
  client: Client;
  assignedUser: User;

  static serialize(data: any): Availability {
    const user: Availability = Object.assign(new this(), data);
    if (data.hasOwnProperty('timestampstart')) {
      user.timestampstart = moment(data.timestampstart);
    }
    if (data.hasOwnProperty('timestampend')) {
      user.timestampend = moment(data.timestampend);
    }
    if (data.hasOwnProperty('serviceType')) {
      user.serviceType = Task.serialize(data.serviceType);
    }
    if (data.hasOwnProperty('client')) {
      user.client = Client.serialize(data.client);
    }
    if (data.hasOwnProperty('assignedUser')) {
      user.assignedUser = User.serialize(data.assignedUser);
    }
    return user;
  }
}

Answer №1

Solving the issue was a breeze once I realized my mistake. As it turns out, in my Angular project, I mistakenly assigned the formControlName to the wrong HTML tag - instead of attaching it to the select tag where it belonged, I attached it to the option tag. This resulted in fetching a value that wasn't what I had anticipated. To rectify this error, I have made adjustments to the main post which now includes the updated code snippet.

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

'Error: The type is missing the 'previous' property - Combining TypeScript with ReactJS'

I am quite new to using reactjs and ts. While I understand the error that is occurring, I am unsure of the best solution to fix it. Currently working with reactjs, I have created an: interface interface IPropertyTax { annul: { current: number; p ...

The name 'Diagnostics' cannot be located

I've downloaded the Typescript repository and am currently reviewing the code. However, I keep encountering this recurring error message: Cannot find name 'Diagnostics' This error pops up on lines that are similar to this: Diagnostics._ ...

When using Material-UI with TypeScript, an error is thrown stating that global is not defined

After running the following commands: npm install --save react react-dom @material-ui/core npm install --save-dev webpack webpack-cli typescript ts-loader @types/react @types/react-dom I transpiled main.tsx: import * as React from "react"; import * as R ...

"What is the purpose of using the `position: absolute` property for movement transitions while deleting an item from a list

Click here to see an example where items smoothly move in a list when one item is removed. To achieve this effect, the element needs to be styled with: .list-complete-leave-active { position: absolute; } I'm curious as to why it doesn't work w ...

Do Angular 2 component getters get reevaluated with each update?

What advantages do getters offer compared to attributes initialized using ngOnInit? ...

Troubles encountered with the search bar filter functionality, implementing JS/JQuery within a Laravel blade template

Currently, I have a blade template containing a search bar for filtering purposes. The issue I'm encountering is that the filtering functionality doesn't seem to work as expected after removing Angular from the page entirely. The page is set up ...

Utilizing a Clear Button to Reset Specific Fields in a Form Without Clearing the Entire Form

I am currently working on a multipart form that includes 'Name', 'Email', and 'Phone Number' fields. It's important to note that the phone number field is actually composed of 10 individual single-digit fields. To enhan ...

What is the reason behind the C# button_clicked function not triggering the Javascript function?

When the user clicks the button, I want to test the C# code side. The method in the C# function should call a JavaScript function to display an alert with the results of a C# public variable. However, it seems that nothing is being called at all. At the bo ...

Unable to retrieve res.user.username while using passport within express-session

I'm currently diving into the realm of creating sessions with Passport.js and Express.js. My goal is to retrieve the username from a user stored in a session using res.user.username, but I seem to be facing some challenges. Below is the snippet of m ...

When using jQuery's `.click()` method on an element to collapse it with the 'show' parameter set to false, the disabling action will only take effect after the document

When you first run the program and click anywhere on the body, it activates the collapse element. I want it to only collapse the accordion on click, not show it immediately. Currently, it will deactivate only after it is hidden once. HTML <!DOCTYPE ht ...

A guide on effectively utilizing nested arrays within a pcolumn prime ng data table

I have a nested array structure and I am utilizing PrimeNG data table to display the data. Below is the organization of my array: this.institutionalTimetable = [ {day: "Monday", entries: [{startTime: "132", endTime: "789", recess: true, subject: 'Eng ...

A step-by-step guide on how to refresh a circular loading indicator

I have been researching how to create a circular progress bar using canvas, and I came across this code. After making some modifications to the code snippets that I found online, I encountered an issue - I can't seem to reload the circular path once i ...

What is a way to hide or exclude tabs when there is no content to display for a particular tab in Vue?

I'm new to javascript and Vue, and I'm trying to figure out how to hide tabs that don't contain any information. I want to display only the tabs that do have information. Can someone please help me with this? I automatically pull images bas ...

Locating all elements on a webpage that are either above or below a specific element, capturing those that intersect visually

Is it possible to locate all the additional HTML elements that a particular element overlaps with, is positioned under, or intersects with? My goal is to ensure that this element is displayed above every other element. I am looking to identify all interse ...

Switch tabs with JavaScript

I'm encountering an issue with changing tabs using JavaScript and Ajax. The script I have works when not using Ajax but fails to work properly with it. Here is the script: $(document).ready(function(){ $("#mtabs li").click(function() { ...

Declaring a function in TypeScript triggers an error notification

I encountered a typescript error while running my code stating that "require" is not a function. To resolve this, I declared the function beforehand; however, a new typescript error now occurs saying "Modifiers cannot appear here." Can anyone assist me w ...

Is there a way to receive messages from background.js of a Chrome Extension within an Angular web application?

I've developed a Chrome Extension that sends messages to all tabs (through background.js) using the following code: chrome.tabs.query({}).then((tabs)=> { if (tabs) { tabs.forEach(tab => { chrome.tabs.sendM ...

In TypeScript, a generic function with an index constraint

Is it possible to define an element that operates in the manner indicated here? function fn<T, U extends keyof T, T[U] extends number>() I am having trouble making the "T[U] extends number" portion function correctly. ...

Encountering TypeScript error TS2345 while attempting to reject a Promise with an error

I recently encountered a perplexing TypeScript error message that I am struggling to comprehend. The specific error reads as follows: error TS2345: Argument of type '(error: Error) => void | Promise' is not assignable to parameter of type & ...

Guide to setting up an express route to utilize passport for secure authentication

I've recently made some adjustments to a boilerplate I created in es6 by downgrading it to an older version, es5. During this process, I had to modify the way I handle exports and requires instead of using imports, but now the routing is working smoot ...