我开始学习棱角,而我正在练习棱角。为此,我创建了一个与表单相关的应用程序。我可以创建一个表单并保存它,然后可以显示它。
我的问题是现在,我试图阻止提交超过20个表格。在20个表格之后,我想显示一条错误消息。
为此,我创建了几个函数,但是它们在HTML中的效果不佳。我的代码在下面。
post-create.component.ts
export class PostCreateComponent {
private postCounter = 0;
@Output() postCreated = new EventEmitter<Post>();
onAddPost(form: NgForm) {
if (form.invalid) {
return;
}
const post: Post = {
title: form.value.title,
content: form.value.content
};
this.postCreated.emit(post);
}
onAddPostCount() {
this.postCounter++;
console.log(this.postCounter);
}
onGetPostCount() {
return this.postCounter;
}
}
post-create.component.html
<mat-card>
<form *ngIf="onGetPostCount() < 20" (submit)="onAddPost(postForm)" #postForm="ngForm" (submit)="onAddPostCount()">
<mat-form-field>
<input
matInput
type="text"
name="title"
ngModel
required>
<mat-error *ngIf="postForm.form.get('title')?.invalid">Please enter a title!</mat-error>
</mat-form-field>
<mat-form-field>
<textarea
matInput
rows="4"
name="content"
ngModel
required
#content="ngModel">
</textarea>
<mat-error *ngIf="content.invalid">Please enter a content!</mat-error>
</mat-form-field>
<button
class="button"
mat-raised-button
color="primary"
type="submit">Save Post
</button>
<mat-error *ngIf="onGetPostCount() > 20"> Count over 2</mat-error>
</form>
</mat-card>
我想知道如何阻止提交超过20个帖子?我该如何修正我的代码,或者有什么方法可以使它变得更快更好?
答案 0 :(得分:1)
我会做这样的事情:
onAddPostCount()
函数。HTML代码:
<mat-card>
<form (submit)="onAddPost(postForm)" #postForm="ngForm">
<mat-form-field>
<input matInput type="text" name="title" ngModel required>
<mat-error *ngIf="postForm.form.get('title')?.invalid">
Please enter a title!
</mat-error>
</mat-form-field>
<mat-form-field>
<textarea matInput rows="4" name="content" ngModel required #content="ngModel">
</textarea>
<mat-error *ngIf="content.invalid">
Please enter a content!
</mat-error>
</mat-form-field>
<br>
<button [disabled]="!isAllowToSubmit" class="button" mat-raised-button color="primary" type="submit">
Save Post
</button>
<button [disabled]="isAllowToSubmit" class="button" mat-raised-button color="primary" type="button" (click)="resetPostCounter()">Reset
</button>
<mat-error *ngIf="!isAllowToSubmit">
Count over 2
</mat-error>
</form>
</mat-card>
TS代码:
private postCounter = 0;
private maximumNoOfPosts = 20;
isAllowToSubmit: boolean = true;
@Output() postCreated = new EventEmitter<any>();
onAddPost(form: NgForm) {
if (form.invalid) {
return;
}
const post: any = {
title: form.value.title,
content: form.value.content
};
this.postCreated.emit(post);
this.onAddPostCount();
}
onAddPostCount() {
if (this.postCounter == this.maximumNoOfPosts) {
this.isAllowToSubmit = false;
}
else {
this.postCounter++;
}
}
resetPostCounter(){
this.postCounter = 0;
this.isAllowToSubmit = true;
}