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")
}
}
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');
}
}