在应用程序组件中提交按钮,并在其他组件中输入。我应该如何验证我的表单“提交”按钮?

时间:2018-09-04 07:39:54

标签: javascript angular

我在应用程序组件中有我的表单,并且我的字段来自另一个具有标签名称 app-check-form-validation 的组件。在使用模板和反应性方法提交时,我应如何验证我的表格。请帮助

Home.component.html

<form class="form-horizontal" [formGroup]="registerForm" 
  (ngSubmit)="onSubmit()">
    <div class="form-group">
        <div class="col-sm-12">
            <app-check-form-validation></app-check-form-validation>
        </div>
    </div>
    <button type="submit" class="btn btn-primary">
        Submit
   </button>
</form>

Home.component.ts

import { Component, OnInit } from '@angular/core';
import {FormGroup, FormBuilder, Validators, FormControl } from 
'@angular/forms';
@Component({
   selector: 'app-home',
   templateUrl: './home.component.html',
   styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
    constructor(private formBuilder: FormBuilder) { }

    ngOnInit() {
       this.registerForm = this.formBuilder.group({
           email: ['', [Validators.required, Validators.email]],
       });
    }
    onSubmit() {
        this.submitted = true;
        // stop here if form is invalid
        if (this.registerForm.invalid) {
            return;
        }
    }

}

check-form-validation.component.html

<label for="email" class="control-label">Email</label>
<input type="text" id="email" class="form-control" formControlName="email">
<div *ngIf="submitted && registerForm.email.errors" class="invalid-feedback">
    <div *ngIf="registerForm.email.errors.required">Email is required</div>
    <div *ngIf="registerForm.email.errors.email">Email must be a valid email 
    address</div>
</div>

check-form-validation.component.ts

import { Component, OnInit } from '@angular/core';
@Component({
    selector: 'app-check-form-validation',
    templateUrl: './check-form-validation.component.html',
    styleUrls: ['./check-form-validation.component.css']
})
export class CheckFormValidationComponent implements OnInit {

    constructor() { }

    ngOnInit() {
    }

}

1 个答案:

答案 0 :(得分:0)

您可以使用具有可观察性的服务。提交的组件可以调用服务功能,而经过验证的组件可以订阅服务并采取适当的措施。

您可以在此处了解有关服务的信息:https://angular.io/tutorial/toh-pt4