我的项目遵循反应形式:
<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 user中写入tagname并按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());
}
}
但这并不止于提交表格。按Enter键
后需要取消提交表格答案 0 :(得分:1)
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());
}
}
<强> Example 强>