0

I'm working through the angular documentation using stackblitz and the two window.alert it had me create so far are not working. The first one was for the "share" button which was really just me adding it to the HTML but the alert is not working when I click the share button. Any tips on troubleshooting?

Here is the component:

import { Component } from '@angular/core';

import { products } from '../products';

@Component({
  selector: 'app-product-list',
  templateUrl: './product-list.component.html',
  styleUrls: ['./product-list.component.css']
})
export class ProductListComponent {
  products = products;

  share() {
    window.alert('The product has been shared!');
  }

  onNotify() {
    window.alert('You will be notified when the product goes on sale');
  }
}

and here is the html:

    <h2>Products</h2>
    
    <div *ngFor="let product of products">
      <h3>
        <a [title]="product.name + ' details'">
          {{ product.name }}
        </a>
      </h3>
    
      <p *ngIf="product.description">
        Description: {{ product.description }}
      </p>
    
      <button (click)="share()">
        Share
      </button>
    
      <app-product-alerts [product]="product" (notify)="onNotify()">
      </app-product-alerts>
    </div>
Heather
  • 3
  • 4

2 Answers2

1

Updated Answer

The issue seems to lie in how stackblitz organizes its code/UI into various frames, which seems to be running afoul of Chrome's security policies. When I click on the button in the stackblitz provided by Robert in the comments, there is no alert dialog and I see the following warning in the console:

A different origin subframe tried to create a JavaScript dialog. This is no longer allowed and was blocked. See https://www.chromestatus.com/feature/5148698084376576 for more details.

Try using a different browser such as Edge, and you should see it working. That being said, I would recommend developing and running locally (which my original answer assumed you were doing) so as to avoid any other "gotchas" that may arise from working in stackblitz. See my original answer below to get it to compile/run on your machine.

Original Answer

I suspect that your app is not compiling (and thus not generating the `alert` code you added), as I had to do the following to get your repo to compile:
  1. Copy tsconfig.json to tsconfig.app.json
  2. npm i -D @angular/cli@12.0.5 @angular/compiler-cli@12.0.5 typescript@4.2

Once I did that and ran npm start, the alerts worked.

David Deutsch
  • 17,443
  • 4
  • 47
  • 54
0

Have you tried only alert() method, although window.alert() should also work. The typescript library provides us a alert() method too. Also, If you could provide a stackblitz link to your code snippets, we can let you know more on your code is not working.

Meanwhile, below is the link to show that window.alert() and alert() both works in angular.

https://stackblitz.com/edit/angular-ivy-byyhco