编辑2:改进了部分解决方案,现在它是一个完整的解决方案。耶!
编辑:找到了一个几乎完整的解决方案。它有效,但不完全是我想要的方式。
解决方案发布在下面的文本之后。
我是 Angular 的新学生,我正在制作一个简单的 CRUD 应用程序来了解该语言的工作原理。目前,我正在学习如何进行表单验证。
正如标题中提到的,我想要一个验证方法来检查输入是否为空,如果是则输入默认值。我正在寻找一种干净而简单的方法来做到这一点。目前这是我的代码。
partial post.component.html(抱歉该<input>元素有多行;我发现这种方式更容易阅读)
<modal #modal>
<form novalidate (ngSubmit)="onSubmit(postForm)" [formGroup]="postForm">
<modal-header [show-close]="true">
<h4 class="modal-title">{{modalTitle}}</h4>
</modal-header>
<modal-body>
<div class="form-group">
<div>
<span>Post Title</span>
<input [(ngModel)]="TitleText"
type="text" class="form-control"
placeholder="Post Title"
formControlName="PostTitle">
<div class="error"
*ngIf="postForm.get('PostTitle').hasError('required') && postForm.get('PostTitle').touched">
Title is required
</div>
<div class="error"
*ngIf="postForm.get('PostTitle').hasError('minlength') && postForm.get('PostTitle').touched">
Minimum title length is three (3) characters
</div>
</div>
<div>
<span>Post Slug</span>
<input [ngModel]="TitleText | slugify"
type="text"
class="form-control"
placeholder="Post Slug"
formControlName="PostSlug">
<div class="error" …Run Code Online (Sandbox Code Playgroud)