簡體   English   中英

在應用程序組件中提交按鈕,並在其他組件中輸入。 我應該如何驗證我的表單“提交”按鈕?

[英]submit button in app component and input in the other component. How should I validate my form On submit button?

我在應用程序組件中有表單,而我的字段來自另一個具有標簽名稱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;
        }
    }

}

檢查外形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>

檢查外形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() {
    }

}

您可以使用具有可觀察性的服務。 提交的組件可以調用服務功能,而經過驗證的組件可以訂閱服務並采取適當的措施。

您可以在這里閱讀有關服務的信息: https : //angular.io/tutorial/toh-pt4

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM