在我的 Angular 17 项目中,我有一个执行重定向的页面。 如果用户在重定向后按后退按钮,因为浏览器(Chrome)正在维护旧值,我希望能够清理输入字段。
经过大量搜索,我找到了这个清洁场地的解决方案:
@ViewChild('iptUrl')
set watch(iptUrl: ElementRef) {
if (iptUrl) {
console.log('test1', iptUrl);
console.log('test2', '#' + iptUrl.nativeElement.value + '#');
// iptUrl.nativeElement.value = '';
// The above line is what I would do to clean the input.
// It's commented so it doesn't interfere in the debugs.
}
}
但是我从调试中得到了不合理的输出: 当我在控制台中展开时,第一个 console.log (test1) 中的
iptUrl
对象的属性 iptUrl.nativeElement
报告该值为 "https://192.168.0.155:4200/feee5230"
。正确的。我想清理旧值。但第二个 console.log (test2) 返回“##”。
如果我尝试做 iptUrl.nativeElement.value = '';
因为我希望什么都不会发生并且输入保持旧值:/
如果我尝试
JSON.stringify(iptUrl)
,这就是控制台中的结果:
{"nativeElement":{"__ngContext__":8,"__zone_symbol__inputfalse":[{"type":"eventTask","state":"scheduled","source":"HTMLInputElement.addEventListener:input","zone":"angular","runCount":0}],"__zone_symbol__blurfalse":[{"type":"eventTask","state":"scheduled","source":"HTMLInputElement.addEventListener:blur","zone":"angular","runCount":0}],"__zone_symbol__compositionstartfalse":[{"type":"eventTask","state":"scheduled","source":"HTMLInputElement.addEventListener:compositionstart","zone":"angular","runCount":0}],"__zone_symbol__compositionendfalse":[{"type":"eventTask","state":"scheduled","source":"HTMLInputElement.addEventListener:compositionend","zone":"angular","runCount":0}],"__zone_symbol__ngModelChangefalse":[{"type":"eventTask","state":"scheduled","source":"HTMLInputElement.addEventListener:ngModelChange","zone":"angular","runCount":0}],"__zone_symbol__keyupfalse":[{"type":"eventTask","state":"scheduled","source":"HTMLInputElement.addEventListener:keyup","zone":"angular","runCount":0}]}}
无价值财产。
上面两个 console.log 调试的输出图像在哪里:
这里发生了什么事?
这是模板中输入的定义:
<input [(ngModel)]="url" (keyup)="validate($event)" #iptUrl id="iptUrl" class="form-control form-control-lg empty" type="text" placeholder="Write here!" aria-label="Write here!" required>
如果有人有更好的方法来清理这个输入,答案也将被接受。
谢谢。
当按下后退按钮时,检查是否按下
ngOnInit
,然后在其中设置此代码。
ngOnInit() {
this.url = '';
}
如果这不起作用,请查看路由器事件。
constructor(router:Router) {
router.events.subscribe(event => {
// also try other events like NavigationEnd, NavigationCancel
if(event instanceof NavigationEnd) {
this.url = '';
}
}
});
还可以尝试重置
ngOnDestroy
上的 URL。