Angular 2中的表单提交状态标志

时间:2017-03-22 00:07:38

标签: angular form-submit ngif

我想显示一个表单提交标记,最终会在用户等待结果时成为动画。

我正在使用以下功能:

  onSubmit(): void {
    console.log(JSON.stringify(this.applicationForm));
    this.formState = 'submitted';


    this.submitService.submitApplicationForm(this.applicationForm)
      .then(
      success => this.handleSubmissionResponse(success),
      failure => this.handleSubmissionResponse(failure)
      );
  }

在我的表单组件类中,我有:

export class SendAnswers implements OnInit {

submitStatus = "We are getting your results..."
status = "submitting"

然后是一个基本功能来改变上面的标签

  submitState(newStatus){
    this.submitStatus = newStatus;
    this.status = (this.status === 'submitting' ? 'We are getting your results...': 'Your results are below');
  }

状态标志:

  <div *ngIf="this.formState === 'submitted'">
      <h3>{{submitStatus}}</h3>
  </div>

如果您的角色2中不再有submitState,我如何在ngIf声明后致电ng-init

1 个答案:

答案 0 :(得分:0)

您是否在我的应用首次加载我的组件时询问如何调用submitState?

如果是这种情况,那么这就是组件上ngOnInit生命周期方法的目的。 Angular在初始化组件时会自动调用此方法。

因此,您可以在ngOnInit方法中添加初始submitState调用。

btw,因为你的组件实现了OnInit接口,所以你的组件上已经存在ngOnInit方法。

修改

因此,假设您的onSubmit和submitState作为组件上的两个方法,您可以将onSubmit调整为:

onSubmit():void {     的console.log(JSON.stringify(this.applicationForm));     // this.formState =&#39;已提交&#39 ;; &lt; ---为什么会在这里?

this.submitState('submitting');

this.submitService.submitApplicationForm(this.applicationForm)
  .then(
  success => {
    this.submitState('submitted');
    this.handleSubmissionResponse(success);
  },
  failure => this.handleSubmissionResponse(failure)
  );

}

submitState(newStatus){
    this.submitStatus = newStatus;
    this.status = (this.status === 'submitting' ? 'We are getting your results...': 'Your results are below');

}