Discovering the current date in Angular 8 by utilizing the form builder

Is there a way to automatically fill a form created with FormBuilder with the system's date and time when it is created, instead of the default date format?

this.creationDate = moment().format(DATE_TIME_FORMAT);

I want to update the creationDate field in my form to capture the current system date and time. Here is an example snippet of code that shows how this can be achieved:

private createFromForm(): IBlog {
  return {
    ...new Blog(),
    id: this.editForm.get(['id']).value,
    creationDate:
      this.editForm.get(['creationDate']).value != null ? moment(this.editForm.get(['creationDate']).value, DATE_TIME_FORMAT) : undefined,
    title: this.editForm.get(['title']).value,
    imageContentType: this.editForm.get(['imageContentType']).value,
    image: this.editForm.get(['image']).value,
    appuserId: this.editForm.get(['appuserId']).value,
    communityId: this.editForm.get(['communityId']).value
  };
}

Answer №1

To ensure the creation date remains accurate and uneditable by users, it is advisable not to include it in a form field. A better approach would be to set the property in the Blog constructor by simply adding

this.creationDate = moment().format(DATE_TIME_FORMAT)
. If you still wish to display it in the form, you can create a new disabled field using:

this.fb.control(new Date())

This prevents users from modifying the creation date they enter.

Please keep in mind that this method is suitable only for forms dedicated to creating new blog posts. When editing existing blog posts, always retrieve the creation date from your chosen persistent storage source.

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

Unable to set a union key type for dynamic objects

Within my object, I am dynamically assigning a field and its corresponding value: type PhoneFields = 'deliveryPhoneNumber' | 'pickupPhoneNumber' (props: { phoneField?: PhoneFields }) { const initialValues = { [props.phoneField ...

Utilize Angular 2 to search and filter information within a component by inputting a search term from another component

In my application, I have a Component named task-board which contains a table as shown below: <tr *ngFor="let task of tasks | taskFilter: searchText" > <td>{{ task.taskName }}</td> <td>{{ task.location }}</td> <td>{{ ta ...

What makes components declared with "customElements.define()" limited in their global usability?

I've been tackling a project in Svelte, but it involves some web components. The current hurdle I'm facing is with web components defined using the customElements.define() function in Typescript, as they are not accessible unless specifically im ...

Encountering an Issue: The formGroup function requires an instance of a FormGroup. Kindly provide one

I am a beginner with Angular 2 and despite reviewing numerous stack overflow answers, I still can't resolve my issue. I have recently started learning about angular reactive forms and wanted to try out my first example but I'm facing some diffic ...

Facing issues with integrating Mixpanel with NestJS as the tracking function cannot be located

While utilizing mixpanel node (yarn add mixpanel) in conjunction with NestJS, I have encountered an issue where only the init function is recognized. Despite calling this function, I am unable to invoke the track function and receive the error message: Ty ...

The function Observable.timer in Angular rxjs is throwing an error when imported

Encountering an error in my Angular application that reads: ERROR TypeError: rxjs_Observable__WEBPACK_IMPORTED_MODULE_4__.Observable.timer is not a function at SwitchMapSubscriber.project (hybrid.effect.ts:20) at SwitchMapSubscriber.push ...

While attempting to send a GET Request in Angular, access to XMLHttpRequest has been denied due to CORS policy restrictions

I am attempting to establish a GET method for my PHP API. Here is the code snippet I am using: export class PerfilComponent { perfil: any; constructor(private http: HttpClient) { } ngOnInit() { const token:string | null = localStorage.getItem(&ap ...

Adjust the size of every card in a row when one card is resized

At the top of the page, I have four cards that are visible. Each card's height adjusts based on its content and will resize when the window size is changed. My goal is to ensure that all cards in the same row have equal heights. To see a demo, visit: ...

Expanding constructor in TypeScript

Can the process described in this answer be achieved using Typescript? Subclassing a Java Builder class This is the base class I have implemented so far: export class ProfileBuilder { name: string; withName(value: string): ProfileBuilder { ...

The value of type 'number' cannot be assigned to type 'string | undefined'

Having an issue with the src attribute. I am trying to display an image on my website using the id number from an API, but when I attempt to do so, it gives me an error in the terminal saying 'Type 'number' is not assignable to type 'st ...

Utilize the Lifecycle Interface within Angular 2 framework for enhanced application development

Can you explain the impact of this rule? "use-lifecycle-interface": true, ...

What is the reason behind the checkbox event status returning the string "on" rather than true/false?

I have implemented a custom checkbox as a child component within a parent component. I properly pass the ngModel, name, etc., and attempt to update the model with a boolean status (true/false) based on the checkbox status using an EventEmitter. However, t ...

What steps are required to transition an Angular application developed without the Angular CLI into an Angular CLI project?

I've created an Angular app using tools like NPM (without utilizing the Angular CLI). What would be the most efficient way to transition this project into the CLI project structure? I want to have the ability to utilize commands like ng serve. ...

Issue encountered: NullInjectorError - R3InjectorError has been caused by a problem within AppModule regarding InjectionToken HTTP_INTERCEPTORS linking to TransferState

Error Image:- Error Images I am encountering this error: ERROR NullInjectorError: R3InjectorError(AppModule)[InjectionToken HTTP_INTERCEPTORS -> [object Object] -> TransferState -> TransferState -> TransferState]: NullInjectorError: No provider ...

Passing a boolean value from the parent Stepper component to a child step in Angular

I am facing an issue with passing the boolean value isNewProposal from a parent Angular Material stepper component to its children steps. Despite using @Input(), the boolean remains undefined in the child component, even after being assigned a value (true ...

Tips for implementing dynamic properties in TypeScript modeling

Is there a way to avoid using ts-ignore when using object properties referenced as strings in TypeScript? For example, if I have something like: const myList = ['aaa', 'bbb', 'ccc']; const appContext = {}; for (let i=0; i< ...

constrain a data structure to exclusively contain elements of a particular data type

interface Person { id:number, name:string } const someFunction(people: ???) => {...} Query: Can the people parameter be typeguarded to only allow an object with all properties matching a Person interface, similar to the following structure: pe ...

The 'authorization' property is not available on the 'Request' object

Here is a code snippet to consider: setContext(async (req, { headers }) => { const token = await getToken(config.resources.gatewayApi.scopes) const completeHeader = { headers: { ...headers, authorization: token ...

Tips for ensuring only one property is present in a Typescript interface

Consider the React component interface below: export interface MyInterface { name: string; isEasy?: boolean; isMedium?: boolean; isHard?: boolean; } This component must accept only one property from isEasy, isMedium, or isHard For example: <M ...

IE11 displaying corrupted characters on every JavaScript file

After attempting to add the meta charset in the html header and charset in script tag, I found that neither solution worked. I am truly puzzled by this. On a side note, the system language is set to Chinese, but changing it to English did not solve the i ...