The error ReferenceError: localStorage is not defined occurs in Angular projects when localStorage is accessed in an environment where it is not available, such as on the server side during server-side rendering (SSR) using Angular Universal. The localStorage API is part of the browser's window object, and it is unavailable in non-browser environments. To fix this error in your Angular 18 project, you can use the following approaches: 1. Check if localStorage Exists Ensure localStorage is accessed only in the browser. Modify your service or component code to check for its availability before using it. if ( typeof window !== 'undefined' && window . localStorage ) { // Access localStorage here localStorage . setItem ( 'key' , 'value' ); } else { console . warn ( 'localStorage is not available.' ); } 2. Use Angular's Dependency Injection for Platform Check Use Angular's PLATFORM_ID to check whether the code is running ...
Call child component method from parent class - Angular In Angular, to share data from a child component to a parent component, the most common approach is using EventEmitter with @Output() . Here's how it works step by step: Steps for Child-to-Parent Data Sharing In the Child Component : You define an EventEmitter using the @Output() decorator to emit the data. In the Parent Component : The parent component listens for the event emitted by the child and handles the data that is sent. Example: 1. Child Component ( child.component.ts ) Here, we want to send data (e.g., a message) from the child component to the parent. typescript import { Component , Output , EventEmitter } from '@angular/core' ; @Component ({ selector : 'app-child' , template : ` <button (click)="sendData()">Send Data to Parent</button> ` , styleUrls : [ './child.component.css' ] }) export class ChildComponent { // Step 1: Declare an EventEmitt...