我的目标是确保用户输入有效数据(无数字),并且在提交表单之前输入字段不应为空。帮助!
ts文件代码如下:
import { Routes, RouterModule, Router, ActivatedRoute } from "@angular/router";
import { Component, NgModule, Input, Output, EventEmitter } from '@angular/core';
import { Environments } from './Environment-class';
import { FormBuilder, FormsModule, ReactiveFormsModule, FormGroup, FormControl, Validators } from '@angular/forms';
@Component({
selector: 'addenvironment-form',
templateUrl: './add-environment-form.component.html'
})
export class AddEnvironmentComponent {
@Output() EnvironementCreated = new EventEmitter<Environments>();
createNewEnv(EnvironmentNames: string) {
this.EnvironementCreated.emit(new Environments(EnvironmentNames));
}
}
和HTML文件
<br />
<div class="card">
<h4 class="card-header">Add a New Environment</h4>
<div class="card-body mx-auto ">
<form class="form-inline ">
<div class="form-group ">
<h5 class="form-control-static">Enter New Name: </h5>
</div>
<div class="form-group mx-lg-3 text-center">
<label for="inputPassword2" class="sr-only">Password</label>
<input type="text" class="form-control " id="inputPassword4" placeholder=" Name " #EnvironmentNames>
</div>
<button type="submit" class="btn btn-primary" (click)="createNewEnv(EnvironmentNames.value)">Submit</button>
</form>
</div>
答案 0 :(得分:2)
您可以将required
标记添加到输入字段,以便填写。
此外,您可以添加minlength
。
要仅使其成为字母,您可以使用pattern
。您可以使用允许用户输入的字符来播放。
如果您打算将此输入用作密码,建议您将type
更改为type="password"
如果表单无效,您还可以disable
按钮。
通过上面提到的所有这些,您的表单看起来应该像下面这样:
<form [formGroup]="myForm" class="form-inline ">
<div class="form-group ">
<h5 class="form-control-static">Enter New Name: </h5>
</div>
<div class="form-group mx-lg-3 text-center">
<label for="inputPassword2" class="sr-only">Password</label>
<input type="password" class="form-control " id="inputPassword4"
placeholder=" Name " #EnvironmentNames pattern="^[a-zA-Z]+$"
minlength="8" required>
</div>
<button type="submit" class="btn btn-primary"
(click)="createNewEnv(EnvironmentNames.value)"
[disabled]="!myForm.valid">Submit
</button>
</form>