在通过编程方式使用响应式表单时,Ionic Angular的 ion-input无法在视觉上重置
我有一个基于Ionic的 Angular应用,包含两个页面(登录和注册),它们共享一个根作用域的服务,该服务持有响应式表单。当通过Ionic的路由在页面之间导航时,ion-input 字段在视觉上没有清空,尽管Angular表单的值已经被正确重置。
设置:
Root服务持有表单:
typescript
@Injectable({ providedIn: 'root' })
export class AuthService {
public signUpForm: FormGroup = this.buildForm();
constructor(private fb: FormBuilder) {}
private buildForm(): FormGroup {
return this.fb.group({
userName: ['', Validators.required],
email: ['', [Validators.required, Validators.email]],
password: ['', Validators.required],
});
}
}
页面使用 ionViewWillEnter 通过视图门面上的信号触发重置:
typescript
@Injectable({ providedIn: 'root' })
export class SignUpViewFacade {
public resetForm = signal(false);
}
typescript
export class SignUpPage {
private facade = inject(SignUpViewFacade);
ionViewWillEnter(): void {
this.facade.resetForm.set(true);
}
}
组件监听信号并重置:
typescript
export class SignUpComponent {
public authService = inject(AuthService);
public viewFacade = inject(SignUpViewFacade);
constructor() {
effect(() => {
const shouldReset = this.viewFacade.resetForm();
if (shouldReset) {
this.authService.signUpForm.reset();
this.authService.signUpForm.markAsPristine();
this.authService.signUpForm.markAsUntouched();
this.viewFacade.resetForm.set(false);
}
});
}
}
模板:
html
<form [formGroup]="authService.signUpForm">
<ion-item>
<ion-input
formControlName="userName"
label="Username"
labelPlacement="floating"
clearInput="true"
></ion-input>
</ion-item>
</form>
我尝试过的办法:
form.reset()— 能正确重置Angular模型(通过日志证实),但ion-input在视觉上仍显示旧值autocomplete="off"和autocomplete="new-password"— 浏览器忽略了这些- 通过
@ViewChildren(IonInput)设置input.value = ''— 不起作用 await input.getInputElement()然后设置原生值 — 也不起作用- 使用随机的
name属性来抵御自动填充 — 也不起作用
解决方案
使用 setValue('') 代替 reset()
有时在显式传入值时,Ionic的反应会更好。
this.authService.signUpForm.patchValue({
userName: '',
email: '',
password: ''
});
this.authService.signUpForm.markAsPristine();
this.authService.signUpForm.markAsUntouched();
或
this.authService.signUpForm.setValue({
userName: '',
email: '',
password: ''
});
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。