【发布时间】:2021-11-02 15:27:13
【问题描述】:
我设置了一个简单的应用程序,由两个组件组成:主应用程序和横幅。横幅在应用程序组件中呈现,其想法是从仪表板组件切换横幅的可见性。
上述方法第一次运行良好(即显示横幅,然后隐藏),但在随后的尝试中,横幅仍然隐藏。下面是代码:
app.compoenent.html
<app-banner [showAlert]="showAlert" [alertMessage]="alertMessage"></app-banner>
<button (click)="onClick()">Apply</button>
app.compoenent.ts
import { Component, VERSION } from '@angular/core';
import { BannerComponent } from './components/banner/banner.component';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
name = 'Angular ' + VERSION.major;
showAlert: boolean = false;
alertMessage: string = '';
onClick() {
this.alertMessage = 'Banner Message';
this.showAlert = true;
}
}
banner.compoenent.html
<div [hidden]="!showAlert">
<div>
<span>
{{alertMessage}}
</span>
<a class="close" (click)="closeAlert()" style="text-decoration: underline">[close]</a>
</div>
</div>
banner.compoenent.ts
import {Component, HostBinding, Input, OnInit} from '@angular/core';
@Component({
selector: 'app-banner',
templateUrl: './banner.component.html',
styleUrls: ['./banner.component.scss']
})
export class BannerComponent implements OnInit {
@Input() alertMessage!: string;
@Input() showAlert: boolean = false;
@Input() open() {
this.showAlert = true;
}
constructor() { }
ngOnInit(): void {
}
closeAlert(): void {
this.showAlert = false;
}
}
在上面的例子中,当按钮被点击时,app.component.ts中会执行如下代码:
this.alertMessage = 'error';
this.showAlert = true;
这正确显示了横幅 div。横幅组件包含一个链接标签,事件处理程序将其 showAlert 属性设置为 false 以隐藏横幅 div - 同样这也可以按预期工作。
但是,现在如果再次单击应用组件中的按钮,即使再次将 showAlert 属性设置为 true,横幅仍将保持隐藏状态。
已经设置了 Stackblitz 来演示:
https://stackblitz.com/edit/angular-ivy-9sadyj
看不到我哪里出错了,欢迎任何见解。
【问题讨论】:
标签: angular