angular window.close不好用
时间: 2024-04-24 19:22:08 浏览: 161
在 Angular 中,使用 `window.close()` 关闭窗口可能会受到浏览器的限制,因为浏览器通常不允许通过 JavaScript 关闭非由 JavaScript 打开的窗口。你可以尝试以下两种方法:
1. 在打开窗口的页面中添加一个按钮,当用户点击该按钮时,关闭窗口。
```html
<button (click)="closeWindow()">Close Window</button>
```
```typescript
import { Component } from '@angular/core';
@Component({
selector: 'app-window',
templateUrl: './window.component.html',
styleUrls: ['./window.component.css']
})
export class WindowComponent {
closeWindow(): void {
window.close();
}
}
```
2. 在打开窗口时,将其存储在变量中,并在需要时使用该变量关闭窗口。这种方法需要在打开窗口时使用 `window.open()` 方法,并将其返回值存储在变量中。
```typescript
import { Component } from '@angular/core';
@Component({
selector: 'app-window',
templateUrl: './window.component.html',
styleUrls: ['./window.component.css']
})
export class WindowComponent {
private popupWindow: Window | null;
openWindow(): void {
this.popupWindow = window.open('https://www.example.com', '_blank', 'width=600,height=400');
}
closeWindow(): void {
if (this.popupWindow) {
this.popupWindow.close();
}
}
}
```
这两种方法都可以在 Angular 中关闭窗口,但第二种方法需要更多的代码来实现。
阅读全文