【发布时间】:2022-08-11 20:32:25
【问题描述】:
所以我有一个 Angular 组件:
<!-- login.component.html -->
...
<!-- switch between login and register mode -->
<a (click)=\"onToggleLoginRegister()\">
{{ isLogin ? \'Register now\' : \'Log in with my account\' }}
</a>
...
<!-- button for action -->
<button (click)=\"onClickLoginRegister()\">{{ submitButtonText }}</button>
// login.component.ts
// ...
export class LoginComponent implements OnInit, AfterViewChecked {
// ...
isLogin: boolean = true;
submitButtonText: string = \"\";
ngAfterViewChecked(): void {
this.submitButtonText = \'Login\';
}
onToggleLoginRegister() {
this.isLogin = !this.isLogin;
this.submitButtonText = this.isLogin ? \'Login\' : \'Register\';
}
onClickLoginRegister() { ... }
}
基本上<a> 充当登录和注册模式之间的切换。当我单击它时,<a> 和 <button> 中的文本应相应更改。但是,只有<a> 中的文本得到更新,<button> 文本始终固定在ngAfterViewChecked() 中分配的初始值。我不知道为什么。
(我这样设计的原因是我需要按钮在其他情况下显示不同的文本)
就像许多帖子所说的那样,我尝试使用ChangeDetecterRef 来强制进行更改检测,但是没有用。
但是,当我交换onToggleLoginRegister() 中的两行时,即在isLogin 之前更新submitButtonText,两个文本都将按预期更新。
所以我想知道行为差异是否是由数据类型的差异引起的(因为<a> 绑定到布尔值,<button> 绑定到字符串)。解决方案是什么?
标签: angular typescript