【发布时间】:2018-07-04 10:22:59
【问题描述】:
我正在使用 Angular 6,我有以下表格
<form (ngSubmit)="onFormSubmit(myForm)" #myForm="ngForm">
first name <input type="text" autofocus id="firstname" required [(ngModel)]="firstname" name="firstname" #firstnameValidityMsg="ngModel" >
<div *ngIf="firstnameValidityMsg.invalid && (firstnameValidityMsg.dirty || firstnameValidityMsg.touched)" >
<div *ngIf="firstnameValidityMsg.errors.required"> first name is required </div>
</div>
<button type="submit" [disabled]="!myForm.form.valid">Submit</button>
<div *ngIf="formSuccess && myForm.touched && myForm.dirty"> {{formSuccessMessage}} </div>
</form>
我的组件是
import { Component, OnInit } from '@angular/core';
import { ProfileService } from '../../services/profile.service';
@Component({
selector: 'app-profile', templateUrl: './profile.component.html',
styleUrls: ['./profile.component.css']
})
export class ProfileComponent implements OnInit {
firstname:String;
formSuccess:boolean=false;
formSuccessMessage:String;
constructor( private profileService: ProfileService) { }
ngOnInit() {
this.profileService.getProfile().subscribe((data) =>{
if(data.success){
this.firstname = data.firstname;
})
}
onFormSubmit(myForm:any){
const user = {
firstname:this.firstname
}
this.profileService.saveProfile(user).subscribe((data) =>{
if(data.success){
this.formSuccessMessage = data.msg;
this.formSuccess = true;
}
else{console.log('server doesn't like you');}
})
}
}
当页面加载时,我会获取一些数据来填写表单。对于表单提交,我更改了formSuccessMessage 和accountsuccess 以反映成功并在表单中显示消息。
问题
我想在点击提交后显示成功消息,然后在触摸表单后隐藏成功消息。这将持续到任何未来的提交或触摸
<div *ngIf="formSuccess && myForm.touched && myForm.dirty"> {{formSuccessMessage}} </div> 无法做到这一点。它确实第一次显示消息,仅此而已。当表单被触摸时,它永远不会隐藏消息,以便在将来的提交中重新显示它。我想由于表单中始终包含数据并且永远不会重置,因此这将不起作用。我找不到任何其他组合来使它起作用。在某些时候,第一次提交后,所有状态都保持不变,您可以使用检查。
<p>myForm.dirty - {{myForm.dirty}}</p>
<p>myForm.pristine - {{myForm.pristine}}</p>
<p>myForm.untouched - {{myForm.untouched}}</p>
<p>myForm.touched - {{myForm.touched}}</p>
<p>formSuccess - {{formSuccess}}</p>
如何解决这个问题?
谢谢
【问题讨论】:
-
请将您的代码添加到stackblitz。
-
我在那里没有帐户。 jsfiddle 可以吗?
-
它可以添加到 jsfiddle 。但您无需登录 stackblitz。
-
@Arash 你好。 This link 可以吗?
-
否,请生成源链接。我需要查看你的源码来调试它。
标签: angular forms validation