0% found this document useful (0 votes)
6 views2 pages

Leave Application Component in Angular

The LeaveApplicationComponent is an Angular component that manages the leave application process for users. It utilizes reactive forms to capture leave details, validates date ranges, and interacts with user and leave services. Upon successful submission, it alerts the user and navigates to the leave applications page.

Uploaded by

Almost Viral
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views2 pages

Leave Application Component in Angular

The LeaveApplicationComponent is an Angular component that manages the leave application process for users. It utilizes reactive forms to capture leave details, validates date ranges, and interacts with user and leave services. Upon successful submission, it alerts the user and navigates to the leave applications page.

Uploaded by

Almost Viral
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

import { Component, OnInit } from '@angular/core';

import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';


import { Router } from '@angular/router';
import { LeaveService } from '../_services/[Link]';
import { StorageService } from '../_services/[Link]';
import { UserService } from '../_services/[Link]';

@Component({
selector: 'app-leave-application',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class LeaveApplicationComponent implements OnInit {
visible = false;
leaveForm: FormGroup;
content?: string;
username?: string;
leaveSubmitted: boolean = false;

constructor(
private router: Router,
private fb: FormBuilder,
private userService: UserService,
private leaveService: LeaveService,
private storageService: StorageService
) {
[Link] = [Link]({
date_debut: ['', [Link]],
date_fin: ['', [Link]],
leaveType: ['', [Link]],
leaveMotive: ['', [Link]],
file1: [''],
recipientsInformation: ['', [Link]]
});
}

ngOnInit(): void {
[Link] = [Link]().username; // Adjust this based on
your storage service
[Link]().subscribe({
next: data => {
[Link] = data;
},
error: err => {
[Link]('Error:', err);
}
});
}

photo: any;
recuperFile(fileInput: any) {
[Link] = [Link][0];
const fileReader = new FileReader();
[Link]([Link]);
[Link] = (e: any) => {
[Link]('[Link]');
[Link]([Link]);
[Link]('file1')?.setValue([Link]);
};
}

modifVisible() {
if ([Link]('leaveType')?.value == 'Casual Leave') {
[Link] = false;
} else {
[Link] = true;
}
}

applyLeave() {
const formValues = [Link];

if ([Link] && [Link] && formValues.date_debut &&


formValues.date_fin && [Link] &&
[Link]) {

if ([Link]('invalidDateRange')) {
[Link]();
} else {
[Link]([Link], formValues).subscribe(

// [Link]();
// [Link](['/home/leave-applications']);

alert('Leave Application Submitted\nYour leave application has been


submitted successfully!');

[Link](['/home/leave-applications']);
}
} else {
alert('Empty Fields\nPlease fill out all fields before submitting.');
}
}

dateRangeValidator(control: FormControl) {
const startDate = [Link]('date_debut')?.value;
const endDate = [Link]('date_fin')?.value;
if (startDate && endDate && new Date(endDate) <= new Date(startDate)) {
return { invalidDateRange: true };
}
return null;
}

showDateRangeAlert() {
alert('Invalid Date Range\nEnd date should be later than start date!');
}
}

Common questions

Powered by AI

The LeaveApplicationComponent provides user feedback through alert messages. When the leave application form is submitted, the component checks the validity of the form and the correctness of mandatory fields. If the submission is successful, an alert displays a message indicating successful submission and subsequent routing to the applications page. In contrast, if required fields are empty or the form has validation errors like an invalid date range, appropriate alert messages are shown to inform users to correct errors before re-submission .

The LeaveApplicationComponent in Angular is responsible for handling the leave application process. It initializes a form using FormBuilder, which includes fields for start date (date_debut), end date (date_fin), leave type (leaveType), leave motive (leaveMotive), and file uploads (file1). It retrieves the current user's username from StorageService and subscribes to user-specific data through UserService. This component also manages form submission, ensuring validation, such as checking for invalid date ranges through a custom dateRangeValidator method, and provides feedback through alerts upon successful or unsuccessful submissions. Additionally, it modifies visibility based on leave type selection and processes file uploads by reading and encoding files with FileReader .

User authentication and personalized data handling are pivotal in the functionality of the LeaveApplicationComponent. By accessing the StorageService to retrieve authenticated user information, the component ensures that only logged-in users can initiate and submit leave applications. This personalization extends to dynamically incorporating user-specific data, such as the username, into the form submission workflow, which enhances security by aligning operations with user authentication sessions. Additionally, using UserService to subscribe to user-specific data ensures that the UI remains relevant and accurate to the individual's context, fostering a tailor-made user experience and ensuring data integrity across user sessions .

The LeaveApplicationComponent alters the visibility of its UI elements based on the selected leave type. Specifically, when the user selects 'Casual Leave' as the leave type, the component sets a 'visible' property to false, potentially hiding certain UI elements. For other leave types, the 'visible' property is set to true, which might reveal additional form fields or information menus related to those leave types .

The LeaveApplicationComponent uses the dateRangeValidator function to ensure valid date ranges. This validator checks whether the end date (date_fin) is later than the start date (date_debut) by comparing the two dates. If the end date is earlier than or equal to the start date, it returns an 'invalidDateRange' error. During form submission, if this error is detected, the component displays an alert message to inform the user to select a proper date range .

Within the ngOnInit lifecycle method, the LeaveApplicationComponent handles error responses and user interactions using the UserService. It subscribes to getUserBoard, a data retrieval observable. In the subscription, a 'next' callback function is used to assign the retrieved data to the 'content' property. Concurrently, an 'error' callback caters to handling errors, specifically outputting error messages to the console with console.error. This approach ensures the component is equipped to display user-specific data or log any issues encountered during data fetching, which improves the component’s robustness against run-time issues .

In the LeaveApplicationComponent, the FileReader API is utilized to process file uploads. When a user selects a file through the input element, the recuperFile method is triggered. This method captures the file via the file input event and assigns it to the 'photo' variable. FileReader is then instantiated and used to read the selected file as a Data URL, which is a Base64 encoded string representing the file's contents. Once the reading process is complete, the result is assigned to the 'file1' form control within the leaveForm, allowing the file data to be included in form submissions .

In the LeaveApplicationComponent's leave application form, the mandatory form controls include 'date_debut' (start date), 'date_fin' (end date), 'leaveType' (type of leave), 'leaveMotive' (reason for leave), and 'recipientsInformation'. The form's mandatory state is enforced using Angular's Validators.required directive within FormBuilder, ensuring that these fields are validated for presence and filled out by users before the form can be successfully submitted .

The LeaveApplicationComponent employs multiple Angular services to enhance its functionalities. It injects the StorageService to retrieve the current user's information, such as the username, which is vital for personalizing the application process. UserService is leveraged to obtain user-specific content through an observable subscription, allowing for asynchronous data handling and reacting to user data changes. The LeaveService is critical for processing the leave applications; it is used to submit the form data, including validating and applying the leave request. These services, used through Angular’s Dependency Injection, enable the component to interact with backend systems and manage state efficiently .

After a successful leave application submission, the LeaveApplicationComponent manages route navigation using Angular's Router. Upon confirming that the form is valid and successfully submitted, the component triggers an alert to inform the user and then activates the router's navigate method to redirect the user to the '/home/leave-applications' path. This ensures that the user is taken back to the main leave applications page after completing a submission .

You might also like