我希望它能帮助别人。
我相信所有经验丰富的开发人员都会找到解决方法。我认为下面的内容会对一些初学者有所帮助。
您可以定义自己的未更改变量作为替代方案,如下所示:
<div [hidden]="q_text.valid || q_text.pristine || isQTextUnTouched" class="warning">
然后在您的输入中添加 (ngModelChange)="onQTextChanged()" ,如下所示:
<input type="text" id="q_text" autocomplete="off" size="40" required
[(ngModel)]="model.q_text" (ngModelChange)="onQTextChanged()"
name="q_text" #q_text="ngModel">
然后添加到 onQTextChanged() 中:
onQTextChanged() {
this.isQTextUnTouched = false;
}
然后每次重置表单时设置 this.isQTextUnTouched = true;
这就对了。
在我的应用程序中,一个组件(LoopQuestions)使用另一个组件(QuestionForm)中定义的表单循环问题。我确实在使用 RxJS 订阅的构造函数中将 this.isQTextUnTouched 重置为 true 。
为此,我使用来自的示例官方文档 https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service,但missioncontrol.component.ts(在我的例子中是LoopQuestions)将QuestionModel的新实例发送到astronaut.component.ts(在我的例子中是QuestionForm),而不是任务。 QuestionForm 不是 astronaut.component.ts 中的任务接受确认,而是确认表单已提交。然后 LoopQuestions 立即再次发送 QuestionModel 的新实例。
LoopQuestions 的构造函数:
constructor(private route: ActivatedRoute, private router: Router, private newPollService: NewPollService) {
newPollService.aQuestionCompleted$.subscribe(
() => {
this.q_number++;
if (this.q_number > this.q_qnty) { this.router.navigate(['/home']); }
this.goToNextQuestion();
});
}
goToNextQuestion() {
const nextQuestion = new QuestionModel( ... your default values ... );
this.newPollService.announceQuestionStart(nextQuestion);
}
QuestionForm 的构造函数:
constructor(
private router: Router,
private newPollService: NewPollService
) {
this.subscription = newPollService.questionLoopStarted$.subscribe(
nextQuestion => {
this.isQTextUnTouched = true;
this.model = nextQuestion;
}
);
}
LoopQuestion 的 html:
<div>
<h4>New question - question # {{q_number}}:</h4>
<app-question-form></app-question-form>
</div>
注意:我没有添加任何类型的 form.reset() 因为它会导致意外的行为。