Angular Getting Started - windows.警报不起作用



我正在使用stackblitz和两个窗口完成angular文档。警报,它让我创建到目前为止都没有工作。第一个是"分享"。按钮,这真的只是我把它添加到HTML,但警告是不工作,当我点击共享按钮。对故障排除有什么建议吗?

组件:

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

这里是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>

更新答案

问题似乎在于stackblitz如何将其代码/UI组织到各种框架中,这似乎与Chrome的安全策略相冲突。当我点击Robert在评论中提供的stackblitz中的按钮时,没有警告对话框,我在控制台中看到以下警告:

一个不同的源子框架试图创建一个JavaScript对话框。这是不允许的,并被阻止了。详见https://www.chromestatus.com/feature/5148698084376576

尝试使用不同的浏览器,如Edge,你应该看到它的工作。话虽如此,我还是建议您在本地开发和运行(我最初的回答是假设您正在这样做),以避免任何其他"陷阱"。这可能是因为在stackblitz工作。请参阅下面我的原始答案,以便在您的机器上编译/运行。

原始回答

我怀疑你的应用程序没有编译(因此没有生成你添加的"警报"代码),因为我不得不做以下事情来编译你的repo:
  1. 复制tsconfig.jsontsconfig.app.json
  2. npm i -D @angular/cli@12.0.5 @angular/compiler-cli@12.0.5 typescript@4.2

一旦我这样做并运行npm start,警报工作。

您是否只尝试过alert()方法,尽管window.alert()也应该可以工作。typescript库也为我们提供了alert()方法。此外,如果你能提供一个链接到你的代码片段,我们可以让你知道更多关于你的代码不工作。

同时,下面的链接显示了window.alert()和alert()在angular中都可以工作。

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

最新更新