小编Isk*_*eza的帖子

Angular 2:检查反应形式的输入是否为空,如果没有给出输入则输入默认值

编辑2:改进了部分解决方案,现在它是一个完整的解决方案。耶!

编辑:找到了一个几乎完整的解决方案。它有效,但不完全是我想要的方式。

  1. 它从加载表单的那一刻起就设置默认值。(不理想)
  2. 如果输入为空/已删除,它不再返回 null(而是返回空字符串)

解决方案发布在下面的文本之后。


我是 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)

typescript angular

6
推荐指数
1
解决办法
10万
查看次数

标签 统计

angular ×1

typescript ×1