我的项目有以下 react 形式:
<form [formGroup]="form" (ngSubmit)="onSubmit()">
<div class="line">
<input class="title" id="title" placeholder="Заголовок вопроса" type="text" formControlName="title">
</div>
<div class="line">
<textarea class="question" name="question" id="question" placeholder="Текст вопроса" formControlName="question" cols="30" rows="10"></textarea>
</div>
<div class="line">
<div class="tags">
<span class="title">Метки</span>
<span class="tag" *ngFor="let tag of tags">{{ tag }} <span class="delete" (click)="deleteTag(tag)">X</span></span>
</div>
<input class="tag" id="tag" placeholder="Введите тег и нажмите enter" type="text" formControlName="tag" #tag (keyup.enter)="addTag($event, tag.value)">
</div>
<div class="line">
<button class="btn btn-common" type="submit" mat-button [disabled]="form.invalid">
Отправить
</button>
</div>
</form>
此表单在组件中初始化:
private form: FormGroup;
ngOnInit() {
this.form = new FormGroup({
'title': new FormControl('', [Validators.required, Validators.minLength(1)]),
'question': new FormControl('', [Validators.required, Validators.minLength(3)]),
'tag': new FormControl()
});
}
在#tag 字段中,用户写入标记名并按Enter 键。表格是提交的。但我需要在按 Enter 键后取消表单提交。
我的尝试:
private addTag(event, tag): void {
console.log(event);
event.preventDefault();
event.stopPropagation();
if(!tag.trim().length) { return; }
this.form.patchValue({tag: ''});
if(this.tags.indexOf(tag) === -1) {
this.tags.push(tag.trim());
}
}
但这并没有停止提交表单。我需要在按回车键后取消提交表单
最佳答案
keyup
事件来不及捕获提交。
我会处理 keydown
事件:
html
(keydown.enter)="addTag($event, tag.value)"
ts
private addTag(event, tag): void {
event.preventDefault();
}
或者你可以返回false
html
(keydown.enter)="!!addTag(tag.value)"
^^^^
convert to boolean
ts
addTag(tag): void {
if(!tag.trim().length) { return; }
this.form.patchValue({tag: ''});
if(this.tags.indexOf(tag) === -1) {
this.tags.push(tag.trim());
}
}
关于javascript - 如何拦截提交表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48040023/