gpt4 book ai didi

Angular 2 : Check if input in reactive form is empty, 如果没有给出输入则输入默认值

转载 作者:太空狗 更新时间:2023-10-29 18:30:32 25 4
gpt4 key购买 nike

编辑 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"
*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

    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();
}

如果 PostContent 我想传递一个默认值和 PostAuthor字段留空。我认为可行的一种方法是在模板中使用默认值,如下所示:

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

但是这不起作用,调试显示仍然返回 null:

It's not passing the value hard-coded(ewww...) in the value attribute

同样,因为如果有人决定输入内容然后将其删除,该解决方案无论如何都会导致问题。

作为引用,这里是整个 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 检查?方法(或者它是功能?)代替?


Potential solution, needs improvement

所以在 addPost() post.component.ts 的一部分在上面,我添加了两行:

    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
}

这基本上是从加载模态框以输入新条目的那一刻起设置值。该值可以从输入中删除,当发生这种情况时,它会被替换为空字符串。我不知道这个空字符串值是从哪里来的。

最佳答案

无论您使用何种“形式”(响应式或模板驱动),如果您只想在输入变空时拥有默认值,则可以使用 ngModelChange事件。必须导入FormsModule虽然到你的模块(你使用这个组件的地方,这个模板作为它的 View )让它工作。使用 ngModel传递初始值,如果有的话。

component

// define the type 
postAuthorInitValue: string;
postAuthorDefaultValue = 'DEFAULT VALUE';
// or initialize it with a value, assign the right type (here I used string type)
// postAuthorInitValue = 'Abc Xyz';

postAuthorChanged(newVal: string): void {
if (newVal) {
this.postAuthorInitValue = newVal;
} else if (newVal === '') {
// here is where we put the default value when the 'newVal' is empty string
this.postAuthorInitValue = this.postAuthorDefaultValue;
} else {
this.postAuthorInitValue = newVal;
}
}

template

<input type="text"
[ngModel]="postAuthorInitValue"
(ngModelChange)="postAuthorChanged($event)"
class="form-control"
placeholder="Post Author"
formControlName="PostAuthor">

另一种选择是使用可以放置在每个 <input type="text"> 上的自定义指令读取其值和默认值并在字段为空时将默认值设置为元素的元素。

希望对您有所帮助。

关于Angular 2 : Check if input in reactive form is empty, 如果没有给出输入则输入默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46457401/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com