javascript - 在应用程序组件中提交按钮并在其他组件中输入。我应该如何在提交按钮上验证我的表单?
问题描述
我在应用程序组件中有我的表单,我的字段来自另一个带有标签名称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() {
}
}
解决方案
您可以使用带有 observable 的服务。提交的组件可以调用服务函数,而验证的组件可以订阅服务并采取适当的行动。
您可以在此处阅读有关服务的信息:https ://angular.io/tutorial/toh-pt4
推荐阅读
- javascript - 在 HTTP 响应中发送大型 csv 文件类型文件
- android - 在从Activity调用的类中创建适配器时,如何访问Activity中的适配器?
- java - 我提到的 MPAndroidChart 值没有出现?
- wcf - 将 WCF 替换为具有关联协议的 gRPC
- sql - SQL Server 中的 Select 语句在使用 where 中的电子邮件获取值时返回 null;无法使用带点的值获取数据
- robotframework - 机器人框架 Telnet:EOFError:telnet 连接关闭
- java - cucumber.runtime.CucumberException:在其他设备上运行时无法实例化类
- java - 为什么使用 JUnit 5 运行此 Spring Data JPA 存储库测试会导致 ParameterResolutionException?
- javascript - 在单页 React 组件 useState 中切换(显示/隐藏)组件 onClick
- c# - 某些字符串的输出