Storage Options for Keeping Data Locally: Local Storage and Session

Here is the HTML code snippet I'm working with:

<h2>Welcome User!!!</h2>
<form class="container" action="/product">
    <div>
        <label for="mail"><b>Email ID: [(ngModel)]</b></label>
        <input type="text" placeholder="Enter email ID" [(ngModel)]="mail" name="mail" required>
        <label for="psw"><b>Phone Number</b></label>
        <input type="text" placeholder="Enter Phone Number" [(ngModel)]="phoneNumber" name="phoneNumber" required>

        <button (click)="myFunc()">NEXT</button>
    </div>
</form>

This is how my TypeScript file looks like:

   import { Component, NgModule, OnInit } from '@angular/core';
import { Router, RouterModule, Routes } from '@angular/router';
import { MyProductPageComponent } from '../my-product-page/my-product-page.component';


@Component({
  selector: 'app-my-home-page',
  templateUrl: './my-home-page.component.html',
  styleUrls: ['./my-home-page.component.css']
})

export class MyHomePageComponent implements OnInit {
  phoneNumber = "";
  mailID = "";

  constructor(private router: Router) {
  }

  ngOnInit(): void {
  }

  myFunc() {
    localStorage.setItem("phoneNumber", this.phoneNumber);
    localStorage.setItem("mail", this.mailID);
    this.router.navigate(['/products']);
  }
}

const routes: Routes = [
  { path: 'MyProductPageComponent', component: MyProductPageComponent },
]

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})

I am trying to extract the Phone number and Email ID entered in the form and store them in Local Storage. Then redirect to the next page. Can someone please assist me? I keep encountering an error message stating "Declaration expected."

Answer №1

To bind the value of an input control, you need to use ngModel and access it in your component.

<h2>Welcome User!!!</h2>
<form class="container" action="/product">
    <div>
        <label for="mail"><b>Email-ID: </b></label>
        <input type="text" [(ngModel)]="mailID" placeholder="Enter mail ID" name="mail" required>
        <label for="psw"><b>Phone Number</b></label>
        <input type="text" placeholder="Enter Phone Number" name="phoneNumber" [(ngModel)]="phoneNumber" required>

        <button (click)="myFunc()">NEXT</button>
    </div>
</form>

Answer №2

  1. Include variables for phone and email in your .ts components

  2. Utilize this to access the variables in myFunc() and retrieve their values

  3. Link the variables to user input using ngModel (apply ngModel to the input, not the label).

  4. Ensure to use

    import { NgModule } from '@angular/core';
    in the app.module, not your component

view operational code example

<h2>Welcome User!!!</h2>
<form class="container" action="/product">
    <div>
        <label for="mail"><b>Email-ID:</b></label>
        <input type="text" placeholder="Enter mail ID"  [(ngModel)]="mail" name="mail" required>
        <label for="psw"><b>Phone Number</b></label>
        <input type="text" placeholder="Enter Phone Number" [(ngModel)]="phoneNumber" name="phoneNumber" required>

        <button (click)="myFunc()">NEXT</button>
    </div>
</form>


  phoneNumber = "";
  mailID = "";
  myFunc() {
    localStorage.setItem("phoneNumber", this.phoneNumber);
    localStorage.setItem("mail", this.mailID);
  }

Answer №3

        In the array of routes, ensure that the path does not contain a component reference but rather use router.navigate('/products') 
       const routes: Routes = [
          { path: 'products', component: MyProductPageComponent },
        ]
Make sure to bind these variables used in the TypeScript file with ngModel utilized in the template 
phoneNumber = "";
mailID = "";

<h2>Greetings User!!!</h2>
<form class="container" action="/product">
    <div>
        <label for="mail"><b>Email-ID: </b></label>
        <input type="text" placeholder="Enter mail ID" [(ngModel)]="mailID" name="mail" required>
        <label for="psw"><b>Phone Number</b></label>
        <input type="text" placeholder="Enter Phone Number" [(ngModel)]="phoneNumber" name="phoneNumber" required>

        <button (click)="myFunc()">PROCEED</button>
    </div>
</form>

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

Sharing data between controllers using factory in AngularJS is not supported

I attempted to share data between two controllers by using a factory. However, it seems that the data is not being shared properly between the two inputs. In the AppCtrl controller, I set Data.FirstName to be equal to lattitude. But when I switch over to ...

Returning a JSON representation of a JavaScript object

In the process of working on a script, I encountered a situation where an $.ajax call had to invoke a function upon success, returning a JavaScript object in JSON format [object object]. However, despite being able to return a well-formatted string, access ...

extract data from a JavaScript object

Currently facing an issue extracting a String name from the JSON object's name. It is necessary to parse this type of JSON response obtained from the server. var response = { hopaopGmailsjIpW: { GmailsjIpW_totalEmails_count: 133, GmailsjIpW ...

Issue with custom Javascript not executing in Internet Explorer versions 9 and 10

Initially, this script is found in the document's head section. <script> document.addEventListener("DOMContentLoaded", function () { var e, t = document.querySelectorAll("div.bounceInDown"); for (var n = 0, r = t.length; n & ...

Utilizing the Bing Translation API to translate an entire webpage

I am currently attempting to use the Bing API to translate an entire webpage instead of using the Bing widget. This is because I want to create a custom design for the translation panel, However, I have been unable to find any resources on how to do this ...

Encountering redundant links during the scraping process

I'm currently working on extracting "a" tags with the class name "featured" from a specific website . Although the code I've written seems to be error-free, it unfortunately duplicates the links. How can I resolve this issue and avoid the duplica ...

Nodemailer is experiencing difficulties when used within the routes directory

Recently, I encountered an issue with my subscribe form. It functions perfectly when called from app.js where the express server is defined. However, when I move subscribe.js to the routes folder and connect both files, it fails to send emails. Upon pressi ...

What is the most effective method for incorporating CSS using Javascript to target a specific aria-label attribute?

Is there a way to add a CSS property to a specific tag with a particular aria-label on document load? My goal is to change the flex order of a section to 2. I need help using JavaScript to target the aria-label 'block 1' so I can set the order t ...

The scrollbar located within a table cell is malfunctioning and unresponsive

In a container with a fixed width of 500px, I have a table that contains a cell with potentially long text. To ensure the long text appears on a single line, I set the white-space: nowrap property. However, this causes the table to adjust its size to accom ...

The border-color feature in Bootstrap 5 does not function properly when applying responsive border-start/end/top/bottom styles

My Objective: For mobile: I want to have borders only at the top and bottom. For desktop: I want borders only at the start and end, in a border-dark color. My Attempts: I have added custom responsive borders to my main.scss file // responsive borders @ ...

AngularJS Bootstrap CSS implementation for Hand Cursor Grab

Is there a way to ensure the cursor is always a hand / grab for sortable containers in AngularJS & Bootstrap? What specific HTML modification would achieve this change? <div ui-sortable="sortableOptions" ng-model="responses" class="container-f ...

Utilizing Angular Dependency Injection for Extending Base Services with Subclasses

My service setup includes a base service and two services that inherit from it: @Injectable({ providedIn: 'root' }) export class BaseService { foo(src?: string){ return `speaking from ${src || 'BaseService'}`; } } @Injectable ...

Removing an object from an array if it does not exist in another array: A step-by-step

Looking to remove an object from an array if it's not present in another array. After doing some research, I came across a similar question on this link, but with a different array source. Below is the example from the link: var check = [1, 2, 3]; ...

Interceptors in axios do not trigger when making requests through a PHP proxy

I am currently working on a React app that will be interacting with services hosted on a remote server. During development on my local machine using the react-scripts server at localhost:3000, I disable CORS in the browser and have no issues with axios f ...

What is the best way to incorporate items into Redux reducers?

Incorporating Redux with Next JS, I am faced with the challenge of adding an array of objects to it. Within my application, there exists a form containing multiple inputs, and in order to accommodate these inputs, I have structured a form consisting of 10 ...

Passing a service from a custom element to a child custom element in Angular involves utilizing the

I have created a demonstration showcasing the creation of 2 custom Angular elements (refer to app.module). Everything is working smoothly, but I encountered a problem: when I provide a service in the parent element (named BarComponent), it does not get rec ...

Ways to handle Sessions in Node.js

I'm attempting to utilize a website within node.js. However, the site is prompting me to enable the storage of session cookies. I attempted to set up a cookie-jar, but I couldn't get it to work. Here is a simplified version of the code that is c ...

Angular - Brilliant time selection tool (BTS) The TimePicker feature fails to automatically switch to selecting minutes after choosing the hour

I'm currently implementing the Amazing time picker in my app and I'm facing an issue where it doesn't automatically switch to minutes after selecting the hour. component.html <input type="time" atp-time-picker formControlName="time" cla ...

The Three.js scene is failing to render properly on subsequent attempts

Currently, I am in the process of developing a web-based height map generator using Three.js. The project involves utilizing multiple canvases to display the generated height map, individual octaves that make up the map, and a separate canvas to showcase h ...

Breaking lines of an HTML tag with attributes according to ESLint rules

I'm having difficulties breaking lines in a html tag with attributes and ternary due to ESLint rules. Can anyone provide guidance on the correct way to format this? What is the proper method for breaking these lines? Update: An error message appears ...