触摸角形时隐藏消息

时间:2018-07-04 10:22:59

标签: angular forms validation

我正在使用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');}
    })
  }    
}

页面加载后,我得到了一些数据来填写表格。对于表单提交,我更改了formSuccessMessageaccountsuccess以反映成功并在表单中显示消息。

问题

我想在单击“提交”后显示成功消息,然后在触摸表单后隐藏成功消息。此操作将在以后进行任何提交或触摸时进行

<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>

如何解决此问题?

谢谢

1 个答案:

答案 0 :(得分:1)

我将有一个布尔值,例如isSubmitted,然后订阅valueChanges指令的NgForm,然后查找值更改的任何时候,将isSubmitted标志设置为false。然后,当提交表单时,当然将标志切换到true……分别导入NgFormViewChild来引用表单。您需要在valueChanges中设置AfterViewInit,因为那是DOM元素可用的时候……

@ViewChild('myForm') myF: NgForm;

ngAfterViewInit() {
  this.myF.valueChanges.subscribe((data) => {
    this.formSuccessMessage = '';
    this.isSubmitted = false;
  });
}

然后您将在模板中拥有...

<div *ngIf="formSuccessMessage && isSubmitted"> {{formSuccessMessage}} </div>

并且如上所述,提交表单时将isSubmitted切换为true。