phos
phos

Reputation: 39

ReferenceError: alert is not defined

when I try to execute my function showWelcomeMessage() via the constructor, I get the error ReferenceError: alert is not defined. What could be the issue ? Im using Angular 19 in VS Code. I also want to execute the function via button call after the constructor call like this <button class="btn btn-success" (click)="showWelcomeMessage()">Show Welcome Text</button>.

@Component({
  selector: 'app-data-binding',
  imports: [],
  templateUrl: './data-binding.component.html',
  styleUrl: './data-binding.component.css'
})
export class DataBindingComponent {

  firstName: string = "Lulu";
  rollNo: number = 121;
  isActive: boolean = true;
  currentDate: Date = new Date();
  myPlaceholder: string = "Enter your name"
  divBlue: string = "bg-primary";

  constructor() {
    console.log(this.firstName)
    this.isActive = false;
    console.log(this.isActive)

    this.showWelcomeMessage() // <------- problem

  }

  showWelcomeMessage () {
    alert("Welcome")
  }

}

Upvotes: 1

Views: 80

Answers (2)

phos
phos

Reputation: 39

This is the solution I came up with:

import { Component, Inject } from '@angular/core';
import { PLATFORM_ID } from '@angular/core'; 
import { isPlatformBrowser } from '@angular/common'; 

@Component({
  selector: 'app-data-binding',
  imports: [],
  templateUrl: './data-binding.component.html',
  styleUrl: './data-binding.component.css'
})
export class DataBindingComponent {

  firstName: string = "Lulu";
  rollNo: number = 121;
  isActive: boolean = true;
  currentDate: Date = new Date();
  myPlaceholder: string = "Enter your name"
  divColor: string = "bg-primary";
  isBrowser: boolean;

  constructor(@Inject(PLATFORM_ID) platformId: Object) { 
    if(this.isBrowser = isPlatformBrowser(platformId)) {
      this.showWelcomeMessage()
    } 
  } 

  showWelcomeMessage() {
      alert('Welcome');
    }
    
}

I can also use the method elsewhere, like in a button:

<button class="btn btn-success" (click)="showWelcomeMessage()">Show Welcome Text</button>

Upvotes: 0

Naren Murali
Naren Murali

Reputation: 55989

Your code is executing on the server (SSR is enabled) and in the server alert, browser, window does not exist.

We can use afterNextRender to execute the code only on the browser, where alert exists.

showWelcomeMessage () {
    afterNextRender(() => {
      alert("Welcome");
    });
}

For button click you can try isPlatformBrowser (Runs only on the browser) or just checking if alert exists, before executing it.

export class AppComponent  { 
  isBrowser: boolean; 
  
  constructor( @Inject(PLATFORM_ID) platformId: Object) { 
    this.isBrowser = isPlatformBrowser(platformId); 
    console.log(this.isBrowser) 
  } 

  buttonCallback() {
    if(alert) {
      alert('Welcome');
    }
  }

  buttonCallback2() {
    if(this.isBrowser) {
      alert('Welcome');
    }
  }

Upvotes: 5

Related Questions