简体   繁体   English

如何知道 Angular (v5) Reactive-Form 是否是从表单字段提交的,而表单字段本身就是一个自定义组件?

[英]How to know if an Angular (v5) Reactive-Form is submitted from a form field which itself is a custom component?

We have an Angular 4 app, where we have a template driven form, which consists of multiple custom components (ie our custom-input tag).我们有一个 Angular 4 应用程序,其中有一个模板驱动的表单,它由多个自定义组件(即我们的自定义输入标签)组成。 Within those custom components we need to know if the form is already submitted or not.在这些自定义组件中,我们需要知道表单是否已经提交。 So we can show some error text, within the component.所以我们可以在组件中显示一些错误文本。 So this logic from our custom component has been working until now with Angular 4 and Template Driven Forms:所以我们自定义组件中的这个逻辑直到现在一直适用于 Angular 4 和模板驱动表单:

const classes = this.elementRef.nativeElement.className;

And classes have for instance ng-dirty, ng-touched, ng-invalid and submitted (when the form is submitted).例如,类有 ng-dirty、ng-touched、ng-invalid 和 submit(提交表单时)。 So angular was adding the class ' submitted ' automatically for every form field, when the form is submitted.因此,当提交表单时,angular 会为每个表单字段自动添加“提交”类。

Now We try to build another Angular app, with Version 5, with reactive forms.现在我们尝试使用响应式形式构建另一个 Angular 应用程序,版本 5。 We have the same concept, but from the components (actually from the html - since we use nativeElement) we somehow do not get any clue about the submit.我们有相同的概念,但从组件(实际上来自 html - 因为我们使用 nativeElement)我们不知何故没有得到任何关于提交的线索。 We can of course give in the information from the form to custom elements, but we dont want to write the same on every form component.我们当然可以将表单中的信息提供给自定义元素,但我们不想在每个表单组件上都编写相同的内容。 Imagine the form has 50 fields..想象一下,表单有 50 个字段。

Is there any other option?还有其他选择吗?

There is no such property which can tell you the form is submitted or not, you need to create a variable and keep status of your form like没有这样的属性可以告诉您表单是否已提交,您需要创建一个变量并保持表单的状态,例如

isSubmitted: boolean = false; isSubmitted: boolean = false;

On save method关于保存方法

save(...){
   this.isSubmitted = true;
   ...............
}

See the below link for more detail请参阅以下链接了解更多详情

angular 5 form validation easiest way angular 5 表单验证最简单的方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM