Javascript 如何提交表格?
我的项目有以下反应形式:Javascript 如何提交表格?,javascript,angular,Javascript,Angular,我的项目有以下反应形式: <form [formGroup]="form" (ngSubmit)="onSubmit()"> <div class="line"> <input class="title" id="title" placeholder="Заголовок вопроса" type="text" formControlName="title"> </div> <div class="line">
<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>
在字段#中标记用户写入标记名并按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());
}
}
但这并没有停止提交表格。我需要在按Enter键后取消提交表单
keyup
事件太晚,无法捕获提交
我将处理keydown
事件:
html
(keydown.enter)="addTag($event, tag.value)"
(keydown.enter)="!!addTag(tag.value)"
^^^^
convert to boolean
ts
private addTag(event, tag): void {
event.preventDefault();
}
addTag(tag): void {
if(!tag.trim().length) { return; }
this.form.patchValue({tag: ''});
if(this.tags.indexOf(tag) === -1) {
this.tags.push(tag.trim());
}
}
或者您可以返回false
html
(keydown.enter)="addTag($event, tag.value)"
(keydown.enter)="!!addTag(tag.value)"
^^^^
convert to boolean
ts
private addTag(event, tag): void {
event.preventDefault();
}
addTag(tag): void {
if(!tag.trim().length) { return; }
this.form.patchValue({tag: ''});
if(this.tags.indexOf(tag) === -1) {
this.tags.push(tag.trim());
}
}
请检查我的答案。我添加了工作示例