Angular 18 CRUD with Local Storage | Angular 18 Tutorial

Angular 18 CRUD with Local Storage | Angular 18 Tutorial

Welcome to Learning Partner

Introduction to the Channel

  • The speaker welcomes viewers back to Learning Partner and encourages new subscribers.
  • The channel has over 3,000 members engaged in live coding sessions.
  • Viewers are invited to join a group for notifications about upcoming sessions.

Overview of the Project

  • The video focuses on creating an Angular 18 CRUD application using local storage.
  • This scenario is common in interviews where candidates must demonstrate practical skills after theoretical assessments.

Understanding Machine Tests in Interviews

Expectations from Candidates

  • Companies may not always provide APIs; they often want to see if candidates can perform CRUD operations without them.
  • Working with local storage or JSON server presents challenges as it requires more code for data manipulation.

Repository Creation on GitHub

  • Candidates are typically asked to create a repository on GitHub and push their project there.
  • Instructions are provided for logging into GitHub and creating a new repository named "angular_18_crud".

Setting Up the Project

Cloning the Repository

  • After creating the repository, the next step is cloning it using the provided URL.

Creating an Angular Project

  • The speaker demonstrates how to create a new Angular project using ng new command followed by the project name.
  • Questions during setup include choosing CSS or other preprocessors; CSS is selected here.

Project Configuration

Managing Node Modules

  • To avoid multiple copies of node modules, symbolic links are created for efficiency.

Opening Project in VS Code

  • Instructions are given on how to open the newly created project folder in Visual Studio Code (VS Code).

Running and Configuring Angular Application

Starting the Application

  • To run the application, users need to ensure they open VS Code correctly before executing ng serve.

Default Page Verification

  • Upon running, users will see a default page indicating that their Angular project is operational.

Integrating Bootstrap into Angular

Installing Bootstrap

  • Users can install Bootstrap via npm by searching for it online and executing npm install bootstrap.

Adding Bootstrap Stylesheets

  • After installation, it's necessary to add Bootstrap paths into angular.json under styles and scripts sections.

Angular 18 Project Setup and CRUD Operations

Overview of Angular 18 Changes

  • Angular 18 does not utilize an app module; instead, it employs an app config and app routes as a constant file.
  • All components in Angular 18 are standalone, simplifying the structure by eliminating the need for multiple components for small operations.

Project Initialization and Repository Linking

  • The project is linked to a repository using terminal commands. Initial steps include checking the status of files and staging them with git add ..
  • A commit is made with a message indicating initial files, followed by adding a remote origin (GitHub repository URL) before pushing changes.

Creating the Employee App UI

  • The focus shifts to completing CRUD operations within the app component, specifically for an employee application scenario.
  • Key fields identified for the employee model include EMP ID, name, city, contact number, email ID, and state. These properties may vary based on company requirements during machine tests.

Defining the Employee Model

  • An employee class is created in TypeScript with appropriate data types for each field: number for EMP ID and string for other attributes.
  • A constructor initializes properties to default values (e.g., empty strings or zero), addressing any errors related to uninitialized properties.

Designing the User Interface

  • The UI design involves creating a responsive layout using rows and columns. A card structure is suggested to display employee information effectively.
  • Emphasis on UI design skills alongside coding capabilities is highlighted as essential during assessments or machine tests. Properly designed interfaces are crucial in real-world applications.

Designing a User Interface for Employee Form

Initial Setup of the Table

  • The design begins with creating a table structure, including headers for serial number, name, contact number, and email ID.
  • A <thead> is established with <tr> and <th> elements to define the columns needed for displaying employee data.

Building the Form Layout

  • The body of the table is initiated as empty; a card layout is introduced to represent new employee information. This includes a header labeled "New Employee."
  • A form is created within this card using Bootstrap classes to enhance styling and responsiveness. Two columns are set up side by side for input fields.

Input Fields Configuration

  • Essential fields such as name, email ID, contact number, city, state, and pin code are added to the form. Each field utilizes appropriate input types (e.g., text boxes).
  • An address field is designated as a text area due to its potential multi-line nature; it also employs Bootstrap's form control class for consistency in design.

Finalizing UI Elements

  • Buttons for resetting and saving the form are included at the bottom of the layout; they utilize Bootstrap button styles (e.g., btn-secondary and btn-success). Padding adjustments ensure proper spacing in the UI.
  • The overall interface is checked visually to confirm that all elements display correctly on-screen without any issues related to size or alignment. Adjustments are made where necessary.

Enhancing Table Visibility

  • To improve visibility of input fields within forms, background colors and border styles are adjusted using CSS overrides on Bootstrap's default classes. This ensures that text boxes stand out clearly against their backgrounds.

Structuring Data Binding

  • Discussion shifts towards binding data from forms into an application context; emphasis is placed on utilizing reactive forms over template-driven forms due to their flexibility in handling complex scenarios in Angular applications.
  • A unique identifier (employee ID) is established for each record which will be crucial when integrating with APIs later on; initialization starts at zero during setup processes.

Implementing Reactive Forms

  • The importance of importing necessary modules like ReactiveFormsModule before proceeding with reactive form creation is highlighted; this sets up foundational structures required for building dynamic forms effectively in Angular applications.

Form Control and Employee Management in Reactive Forms

Creating and Initializing the Employee Object

  • The interface for form control has been created, allowing for object initialization within the context of a reactive form.
  • An employee object is defined using the employee model class, which can be instantiated with new employee model(). This approach is standard in industrial projects.

Binding Form Controls to Employee Data

  • Each field (e.g., name, city, address) is initialized as a new form control. The controls are bound to properties of the employee object for data management.
  • Multiple fields such as contact number, email ID, PIN code, and state are mentioned; developers should efficiently create these controls by copying existing ones.

Setting Up HTML Form Structure

  • A <form> tag must encapsulate all elements of the reactive form including buttons. This ensures proper binding between the HTML structure and Angular's reactive forms.
  • The form group is linked to an element using [formGroup]="employeeForm", establishing a connection between the template and component logic.

Error Handling During Initialization

  • An error may occur if the form group is not properly initialized. To resolve this, ensure that it’s set up correctly with new FormGroup() during component initialization.

Streamlining Input Field Bindings

  • Each input field requires a corresponding formControlName attribute to bind it to specific properties in the employee object.
  • Developers are encouraged to use shortcuts for efficiency when creating multiple input fields by copying existing configurations.

Saving Employee Data Locally

  • On clicking "Save," an event triggers a function that saves employee data into local storage. Unique IDs are generated based on existing records in local storage.
  • The process involves checking how many records exist in local storage to assign unique IDs incrementally (e.g., if one record exists, assign ID 2).

Managing Local Storage Data

  • When retrieving data from local storage, it’s essential to check if any data exists before processing it further. If present, convert it back into an array format using JSON methods.

Updating Form Controls with New Data

  • New values are set in specific form controls using methods like .setValue(), ensuring that each control reflects updated information accurately based on user input or stored data.

Employee Data Management in Angular

Initializing Employee Data

  • The employee model is defined with a data type, and upon page load, the local storage data will be read into the application.
  • In the constructor, local storage data is accessed. If data exists, it is assigned to a variable; otherwise, an empty employee list is initialized.

Handling Form Submission

  • When saving new employee data, if no existing records are found in local storage (i.e., first-time entry), the default employee ID starts at zero.
  • Debugging tools are added to track code execution during form submission and local storage interactions.

Local Storage Operations

  • Upon reloading the component, if no data exists in local storage for the specified key, null is returned. This indicates that no previous entries were made.
  • A sample record is created with various fields (name, email ID, contact number). On clicking save, debugging confirms that local storage remains empty initially.

Saving New Records

  • After filling out the form and clicking save, the entered values are pushed into an array representing the employee list.
  • The updated array must be stored back into local storage using localStorage.setItem(), ensuring that it’s converted to string format via JSON.stringify().

Retrieving and Displaying Data

  • After saving a new record successfully, checking local storage shows that an array has been created containing one element.
  • Reloading reveals that previously saved records appear as strings in local storage but can be parsed back into an array format using JSON.parse().

Updating Employee Records

  • When adding another record (e.g., for "Aditya"), it updates IDs based on existing records. The unique ID increments correctly as per current entries.
  • The application now holds two records in total after successful saves. Each record's details reflect accurately within both the application state and local storage.

Angular Iteration Techniques

  • With Angular 18's control flow statements introduced from version 17 onwards, iteration over lists can be done using @for syntax directly within templates.

Creating and Managing Employee Records

Displaying Information from Local Storage

  • The process begins with pasting a contact number and email ID to check if the information can be displayed. The local storage data is utilized to create a new record.

Editing and Deleting Records

  • After successfully saving data, the next step involves adding functionality for editing and deleting records by introducing additional columns in the HTML for action buttons.

Implementing Edit Functionality

  • New buttons for "Edit" and "Delete" are created, styled appropriately, and aligned to center. This design aspect is crucial as it reflects on coding assessments during tests.

Handling Edit Actions

  • An edit function is triggered upon clicking the edit button, passing the current item object to initialize the form with existing values.

Update vs Save Logic

  • A distinction between save mode (when employee ID is zero) and update mode (when employee ID is one) is established. This logic determines which button ("Save Employee" or "Update Employee") should be displayed based on the state of the form.

Updating Records in Array

  • When updating records, it's essential to find the specific entry within an array using unique employee IDs. This ensures that only relevant data gets modified without affecting other entries.

Error Handling During Updates

  • It’s emphasized that checks for undefined values must be included when filtering data. If no matching record exists, appropriate handling prevents errors during updates.

Finalizing Update Process

  • Upon successful updates, reinitialization of the employee model occurs to reset form fields. The code structure may need optimization but focuses first on completing basic functionalities.

Debugging Issues with Updates

Debugging and Updating Employee Records

Debugging the Edit Functionality

  • The speaker identifies an issue with the edit functionality, suggesting to add a debugger to track the problem when clicking "edit."
  • A case sensitivity error is noted where 'employee' is used inconsistently (capitalization), leading to issues in updating records.
  • After correcting capitalization, the update function works as expected, allowing for successful record updates.

Implementing Delete Functionality

  • The speaker discusses creating a delete function that requires passing either the entire object or just the employee ID.
  • A confirmation popup is introduced to ensure user intent before deletion, using JavaScript's confirm method.
  • If confirmed, the function locates the index of the employee in an array and removes it from local storage.

Validation Implementation

  • The speaker transitions into form validation by adding required fields for name and pin code within a form structure.
  • Minimum length validation is set for pin codes (six characters), ensuring data integrity during input.
  • Conditional rendering of validation messages is discussed, showing errors based on user interaction with form fields.

Enhancing User Experience with Form Controls

  • The importance of disabling buttons when forms are invalid is highlighted; this prevents submission until all criteria are met.
  • Upon entering valid data, buttons become enabled again, demonstrating dynamic feedback based on user input.

Resetting Forms and Final Adjustments

  • A reset function is proposed to clear forms after submission or cancellation, streamlining user experience.
  • Attention to detail regarding button types (ensuring they are set correctly to avoid default behaviors like submission).
Video description

Angular 18 CRUD with Local Storage. I have explained from scratch How to Complete Crud Application with Local Storage. How To create Repository on GitHub. How to Clone Repository. CRUD operation with local-storage. To Connect with me & get Notification of Live Session Join https://chat.whatsapp.com/KFcr0qWZkHnKr1jVvzACyr Angular 18 Tutorial https://youtu.be/QjaNv7s1gW0 JavaScript Tutorial in Hindi https://youtu.be/rWhhxVLX2uU Angular 18 Tutorial in Hindi PlayList https://www.youtube.com/playlist?list=PL7JmcZV0UQtUxsHS8dF3EINHdoIvRS6Ft angular 18 tutorial with project | angular real time projects | angular project ideas | angular project for experienced | angular sample project step by step | angular project with source code | Angular crud | Angular crud with local Storage | Crud with local Storage | Angular Crud with Reactive Form | Student Registration app Angular | Employee Registration App Angular Visit Our Mini Project Ideas Portal where you can find So many project ideas you can try to implement https://miniprojectideas.com Follow & Connect me on LinkedIn https://www.linkedin.com/in/chetan-jogi-a87148ba #angular #angular18 #angularproject