【问题标题】:Interpolated string not updated properly in AngularAngular 中的插值字符串未正确更新
【发布时间】: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() { ... }
}

基本上&lt;a&gt; 充当登录和注册模式之间的切换。当我单击它时,&lt;a&gt;&lt;button&gt; 中的文本应相应更改。但是,只有&lt;a&gt; 中的文本得到更新,&lt;button&gt; 文本始终固定在ngAfterViewChecked() 中分配的初始值。我不知道为什么。

(我这样设计的原因是我需要按钮在其他情况下显示不同的文本)

就像许多帖子所说的那样,我尝试使用ChangeDetecterRef 来强制进行更改检测,但是没有用。

但是,当我交换onToggleLoginRegister() 中的两行时,即在isLogin 之前更新submitButtonText,两个文本都将按预期更新。

所以我想知道行为差异是否是由数据类型的差异引起的(因为&lt;a&gt; 绑定到布尔值,&lt;button&gt; 绑定到字符串)。解决方案是什么?

    标签: angular typescript


    【解决方案1】:

    您的三元表达式是向后的,因为您在调用它之前刚刚反转了布尔值 isLogin。

            this.submitButtonText = this.isLogin ? 'Login' : 'Register';
    

    应该

            this.submitButtonText = this.isLogin ? 'Register' : 'Login';
    

    【讨论】:

      猜你喜欢
      • 2017-09-29
      • 1970-01-01
      • 1970-01-01
      • 2021-05-03
      • 2023-02-20
      • 1970-01-01
      • 1970-01-01
      • 2017-06-25
      • 1970-01-01
      相关资源
      最近更新 更多