我有一个简单的登录表单,其中用户名和密码是信号,然后我有一个计算属性,它显示登录按钮是否启用。
username = signal('')
password = signal('')
isDisabled = computed(() => {
const username = this.username()
const password = this.password()
return username == '' || password = ''
})
我将控制台输出放在各处,当我第一次加载页面时,每个更改都会显示在控制台中,并显示 isDisabled 已重新计算。然后我离开该页面并以一定角度导航回该页面(无需硬重新加载)。
现在输入仍然会触发用户名和密码信号更改,但不再调用compute()函数。
我现在使用的是 Angular 版本 17.3.9。
您在条件检查中缺少
=
。请参阅以下工作示例以供参考。
如果问题仍然发生,请分享回 stackblitz 并复制问题。
import {
Component,
model,
Injectable,
inject,
ModelSignal,
signal,
WritableSignal,
computed,
} from '@angular/core';
import { RouterModule, RouterOutlet, provideRouter } from '@angular/router';
import { FormsModule } from '@angular/forms';
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';
@Component({
selector: 'app-dummy',
imports: [RouterModule, FormsModule],
standalone: true,
template: `dummy
<a routerLink="/login"> go to login</a>`,
})
export class Dummy {}
@Component({
selector: 'app-login',
imports: [RouterModule, FormsModule],
standalone: true,
template: `<router-outlet/>
<input [(ngModel)]="username"/><br/>
<input [(ngModel)]="password"/><br/>
<button [disabled]="isDisabled()">submit</button>
<a routerLink="/dummy"> go to dummy</a>
`,
})
export class Login {
username = signal('');
password = signal('');
isDisabled = computed(() => {
const username = this.username();
const password = this.password();
return username === '' || password === '';
});
}
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterModule],
template: `
<router-outlet/>
`,
})
export class App {}
bootstrapApplication(App, {
providers: [
provideRouter([
{ path: 'login', component: Login },
{ path: 'dummy', component: Dummy },
{ path: '', redirectTo: 'login', pathMatch: 'full' },
]),
],
});