首页 > 解决方案 > 在应用程序组件中提交按钮并在其他组件中输入。我应该如何在提交按钮上验证我的表单?

问题描述

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

主页.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>

主页.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;
        }
    }

}

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

检查表单验证.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() {
    }

}

标签: javascriptangular

解决方案


您可以使用带有 observable 的服务。提交的组件可以调用服务函数,而验证的组件可以订阅服务并采取适当的行动。

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


推荐阅读