Isk*_*eza 6 typescript angular
编辑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"
*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>
Run Code Online (Sandbox Code Playgroud)
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();
}
Run Code Online (Sandbox Code Playgroud)
PostContent如果和PostAuthor字段留空,我希望传递默认值。我认为可行的一种方法是在模板中设置默认值,如下所示:
<textarea class="form-control"
placeholder="Post Content"
formControlName="PostContent"
value="Not Set">
Run Code Online (Sandbox Code Playgroud)
然而这不起作用,调试显示仍然返回 null:
没关系,因为如果有人决定输入某些内容然后将其删除,那么该解决方案无论如何都会引起问题。
作为参考,以下是全文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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我应该考虑在onSubmit方法中添加 Null 检查(或者它是函数吗?)?
潜在的解决方案,需要改进
所以在上面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
}
Run Code Online (Sandbox Code Playgroud)
这基本上设置了从加载用于输入新条目的模式框那一刻起的值。该值可以从输入中删除,当发生这种情况时,它会被替换为空字符串。我不知道这个空字符串值是从哪里来的。
好吧,我已经找到了一个优雅的解决方案。基本上,我需要在加载表单时设置初始值。为此,我添加了对表单控件使用 setValue 方法。
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
}
Run Code Online (Sandbox Code Playgroud)
这样做似乎以一种笨拙的方式解决了这个问题。该值已预先填充在相关输入字段中,如果删除该值,则该值将变为空字符串。这并不理想。
所以我翻转了一下,这样做了:
this.postForm.controls['PostContent'].setValue('');
this.postForm.controls['PostAuthor'].setValue('');
Run Code Online (Sandbox Code Playgroud)
这里我将值设置为空字符串。它不为空,但输入字段未预先填充,并且我的placeholder值仍然可见。出色的。但是空字符串呢?
我们在数据传递到执行 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');
}
. . .
Run Code Online (Sandbox Code Playgroud)
发生的情况是,如果为这些特定键传递的值是空字符串,则将该值设置为默认值。
我认为这是处理这个问题的好方法。它很干净,虽然我不确定是否可以做到这一点,但从理论上讲,将所有默认值放入键值对数组并以这种方式访问它应该不难。
| 归档时间: |
|
| 查看次数: |
99067 次 |
| 最近记录: |