кнопка отправки в компоненте приложения и ввод в другом компоненте. Как мне проверить свою форму на кнопке отправки? - PullRequest
0 голосов
/ 04 сентября 2018

У меня есть форма в компоненте приложения, и мое поле поступает из другого компонента с именем тега 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() {
    }

}

1 Ответ

0 голосов
/ 04 сентября 2018

Вы можете использовать сервис с наблюдаемой. Компонент, который отправляет, может вызывать сервисную функцию, в то время как тот, который проверяет, может подписаться на сервис и предпринимать соответствующие действия.

Об услугах вы можете прочитать здесь: https://angular.io/tutorial/toh-pt4

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...