角度2:检查反应形式的输入是否为空,如果未提供输入,则输入默认值 [英] Angular 2: Check if input in reactive form is empty, enter default value if no input given

查看:76
本文介绍了角度2:检查反应形式的输入是否为空,如果未提供输入,则输入默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

改进了部分解决方案,现在它是一个完整的解决方案.是的!

Edit 2: Improved upon the partial solution and now it's a complete solution. Yay!

编辑:找到了几乎完整的解决方案.它可以工作,但不是我想要的那样.

Found an almost complete solution. It works, but not quite the way I want it.

  1. 它从加载表单开始设置默认值. (不理想)
  2. 如果输入为空/删除,它将不再返回null(而是返回一个空字符串)

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

The solution is posted after the text below.

我是Angular的新学生,我正在制作一个简单的CRUD应用程序以了解该语言的工作原理.目前,我正在学习如何进行表单验证.

I'm a new student to Angular and I'm making a simple CRUD app to understand how the language works. Currently, I'm learning how to do form validations.

如标题中所述,我想拥有一种验证方法,该方法检查输入是否为空,然后输入默认值.我正在寻找一种干净简单的方法来做到这一点.目前,这是我的代码.

As mentioned in the title, I want to have a validation method that checks if the input is empty, and if it is then to enter a default value. I'm looking for a clean and simple way to do this. Currently here is my code.

partial post.component.html (对<input>元素的多行表示抱歉;我发现这样更容易阅读)

partial post.component.html (sorry about the multiple lines for the <input>element; I find it easier to read this way)

<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"
                         *ngIf="postForm.get('PostSlug').hasError('pattern') && postForm.get('PostSlug').dirty">
                        URL slug must not contain spaces, special characters or capitalization
                    </div>
                </div>
                <div>
                    <span>Post Content</span>
                    <textarea class="form-control"
                              placeholder="Post Content"
                              formControlName="PostContent">
                    </textarea>
                </div>
                <div>
                    <span>Post Author</span>
                    <input type="text"
                           class="form-control"
                           placeholder="Post Author"
                           formControlName="PostAuthor">
                </div>
            </div>
        </modal-body>
        <modal-footer>
            <div>
                <a class="btn btn-default" (click)="modal.dismiss()">Cancel</a>
                <button type="submit"
                        [disabled]="postForm.invalid"
                        class="btn btn-primary">
                    {{modalBtnTitle}}
                </button>
            </div>
        </modal-footer>
    </form>
</modal>

partial post.component.ts

partial post.component.ts

    ngOnInit(): void {

        this.postForm = this.fb.group({
            PostId: [''],
            PostTitle: [
                '',
                [
                    Validators.required,
                    Validators.minLength(3)
                ]
            ],
            PostSlug: [
                '',
                [
                    Validators.required,
                    Validators.pattern('^[a-z0-9-]+$')
                ]
            ],
            PostContent: [''],
            PostAuthor: ['']
        });

        this.LoadPosts();
    }

如果PostContentPostAuthor字段留空,我希望传递默认值.我认为可行的一种方法是在模板中设置默认值,如下所示:

I would like a default value to be passed if the PostContent and PostAuthor fields are left empty. One way that I thought would have worked was to have a default value in the template like so:

<textarea class="form-control"
    placeholder="Post Content"
    formControlName="PostContent"
    value="Not Set">

但是这不起作用,并且调试它表明仍然返回null:

However this doesn't work and debugging it shows that null is still returned:

也是如此,因为如果有人决定键入某些内容然后将其删除,那么该解决方案无论如何都会引起问题.

Just as well, because that solution would have caused a problem anyway if someone decided to type something then delete it.

作为参考,这里是整个post.component.ts:

For reference, here's the whole post.component.ts:

import { Component, OnInit, ViewChild, Pipe } from '@angular/core';
import { PostService } from '../Services/post.service';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal';
import { IPost } from '../Models/post';
import { DBOperation } from '../Shared/enum';
import { Observable } from 'rxjs/Rx';
import { Global } from '../Shared/global';

@Component({
    templateUrl: '/app/Components/post.component.html'
})

export class PostComponent implements OnInit {
    @ViewChild('modal') modal: ModalComponent;
    posts: IPost[];
    post: IPost;
    msg: string;
    indLoading: boolean = false;
    postForm: FormGroup;
    dbops: DBOperation;
    modalTitle: string;
    modalBtnTitle: string;    

    constructor(private fb: FormBuilder, private _postService: PostService) { }

    ngOnInit(): void {

        this.postForm = this.fb.group({
            PostId: [''],
            PostTitle: [
                '',
                [
                    Validators.required,
                    Validators.minLength(3)
                ]
            ],
            PostSlug: [
                '',
                [
                    Validators.required,
                    Validators.pattern('^[a-z0-9-]+$')
                ]
            ],
            PostContent: [''],
            PostAuthor: ['']
        });

        this.LoadPosts();
    }

    LoadPosts(): void {
        this.indLoading = true;
        this._postService.get(Global.BASE_POST_ENDPOINT)
            .subscribe(posts => { this.posts = posts; this.indLoading = false; },
            error => this.msg = <any>error);
    }

    addPost() {
        this.dbops = DBOperation.create;
        this.SetControlsState(true);
        this.modalTitle = "Add New Post";
        this.modalBtnTitle = "Add";
        this.postForm.reset();
        this.modal.open();        
    }

    editPost(id: number) {
        this.dbops = DBOperation.update;
        this.SetControlsState(true);
        this.modalTitle = "Edit Post";
        this.modalBtnTitle = "Update";
        this.post = this.posts.filter(x => x.PostId == id)[0];
        this.postForm.setValue(this.post);
        this.modal.open();
    }

    deletePost(id: number) {
        this.dbops = DBOperation.delete;
        this.SetControlsState(false);
        this.modalTitle = "Confirm Post Deletion?";
        this.modalBtnTitle = "Delete";
        this.post = this.posts.filter(x => x.PostId == id)[0];
        this.postForm.setValue(this.post);
        this.modal.open();
    }

    SetControlsState(isEnable: boolean) {
        isEnable ? this.postForm.enable() : this.postForm.disable();
    }

    onSubmit(formData: any) {
        this.msg = "";

        switch (this.dbops) {

            case DBOperation.create:
                this._postService.post(Global.BASE_POST_ENDPOINT, formData._value).subscribe(
                    data => {
                        if (data == 1) //Success
                        {
                            this.msg = "Post successfully added.";
                            this.LoadPosts();
                        }
                        else {
                            this.msg = "There is an issue with creating the post, please contact the system administrator!"
                        }

                        this.modal.dismiss();
                    },
                    error => {
                        this.msg = error;
                    }
                );
                break;

            case DBOperation.update:
                this._postService.put(Global.BASE_POST_ENDPOINT, formData._value.PostId, formData._value).subscribe(
                    data => {
                        if (data == 1) //Success
                        {
                            this.msg = "Post successfully updated.";
                            this.LoadPosts();
                        }
                        else {
                            this.msg = "There is an issue with updating the post, please contact the system administrator!"
                        }

                        this.modal.dismiss();
                    },
                    error => {
                        this.msg = error;
                    }
                );
                break;

            case DBOperation.delete:
                this._postService.delete(Global.BASE_POST_ENDPOINT, formData._value.PostId).subscribe(
                    data => {
                        if (data == 1) //Success
                        {
                            this.msg = "Post successfully deleted.";
                            this.LoadPosts();
                        }
                        else {
                            this.msg = "There is an issue with deleting the post, please contact the system administrator!"
                        }

                        this.modal.dismiss();
                    },
                    error => {
                        this.msg = error;
                    }
                );
                break;
        }
    }
}

我应该考虑在onSubmit方法中添加Null检查吗(或者它起作用吗?)?

Should I look into adding the Null check in the onSubmit method (or is it function?) instead?

潜在的解决方案,需要改进

Potential solution, needs improvement

因此,在上面post.component.tsaddPost()部分中,我添加了两行:

So in the addPost() part of the post.component.ts above, I added two lines:

    addPost() {
        this.dbops = DBOperation.create;
        this.SetControlsState(true);
        this.modalTitle = "Add New Post";
        this.modalBtnTitle = "Add";
        this.postForm.reset();
        this.modal.open();
        this.postForm.controls['PostContent'].setValue('not set'); //this here is the magic
        this.postForm.controls['PostAuthor'].setValue('not credited'); // and this too
    }

这基本上是从模态框输入新条目的那一刻起设置值.可以从输入中删除该值,然后将其替换为空字符串.我不知道这个空字符串值从哪里来.

This basically sets the value from the moment the modal box to enter a new entry is loaded. The value can be deleted from the input and when that happens it's replaced with an empty string. I don't know where this empty string value is coming from.

推荐答案

好的,所以我找到了一个优雅的解决方案.基本上,我需要在加载表单时设置初始值.为此,我将setValue方法用于表单控件.

Alright, so I've found an elegant solution for this. Basically, I need to set the initial value when the form is loaded. To do this, I add use the setValue method for the form controls.

addPost() {
    this.dbops = DBOperation.create;
    this.SetControlsState(true);
    this.modalTitle = "Add New Post";
    this.modalBtnTitle = "Add";
    this.postForm.reset();
    this.modal.open();
    this.postForm.controls['PostContent'].setValue('not set'); //this here is the magic
    this.postForm.controls['PostAuthor'].setValue('not credited'); // and this too
}

这样做似乎以笨拙的方式解决了它.该值已预先填充在相关的输入字段中,如果将其删除,则该值将成为一个空字符串.这不理想.

Doing this seemed to have solved it in a clunky way. The value is pre-populated in the relevant input fields and if it is deleted, then the value becomes an empty string. This is not ideal.

所以我把它翻转过来,是这样的:

So I flipped it around and did it this way:

    this.postForm.controls['PostContent'].setValue('');
    this.postForm.controls['PostAuthor'].setValue('');

在这里,我将值设置为空字符串.它不是空值,但是没有预填充输入字段,并且我的placeholder值仍然可见.出色的.但是空字符串呢?

Here I set the value to an empty string. It's not null, but the input fields are not pre-populated and my placeholder value is still visible. Excellent. But what about the empty string?

在将数据传递到执行HttpPost的服务之前,我们要进行处理.

We handle that before the data gets passed to the service that does the HttpPost.

onSubmit(formData: any) {
    this.msg = "";

    if (formData._value.PostContent == "")
    {
        this.postForm.controls['PostContent'].setValue('not set');
    }
    if (formData._value.PostAuthor == "") 
    {
        this.postForm.controls['PostAuthor'].setValue('not credited');
    }   
    . . .

会发生什么,如果为这些特定键传递的值是一个空字符串,然后将该值设置为默认值.

What happens is if the value being passed for those specific keys is an empty string, then set the value to the default.

我认为这是处理此问题的好方法.这很干净,尽管我不确定是否可以这样做,但从理论上讲,将所有默认值放入键值对数组并以这种方式访问​​它应该并不困难.

I think this is a great way to handle this. It's clean and though I am not sure if it's possible to do this, in theory it should not be difficult to put all the default values in a key-value-pair array and access it that way.

这篇关于角度2:检查反应形式的输入是否为空,如果未提供输入,则输入默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆