按下Enter
键时,PrimeNG Chips组件会添加一个标签。我也想在输入分号后接受标签。按下分号键时是否可以触发Enter
键?
semicolumn(e) {
if (e.key == ';') {
}
}
<p-chips [addOnTab]="true" [addOnBlur]="true" (keydown)="semicolumn($event)"></p-chips>
例如,当用户键入test;
时,就像他键入了test
,然后键入了Enter
。
答案 0 :(得分:1)
触发 Enter 键事件似乎很棘手。但是,由于您在PrimeNG Chips组件上设置了addOnBlur
选项:
<p-chips [addOnTab]="true" [addOnBlur]="true" (keydown)="onKeyDown($event)" ></p-chips>
键入分号时,您可以通过在输入元素上依次调用blur()
和focus()
来接受标签:
onKeyDown(event: KeyboardEvent) {
if (event.key === ";") {
event.preventDefault();
const element = event.target as HTMLElement;
element.blur();
element.focus();
}
}
有关演示,请参见this stackblitz。
答案 1 :(得分:0)
您可以使用@ViewChild
并控制primeng
组件:
my-comp.component.ts
import { Chips } from 'primeng/chips';
import { Component, OnInit, ViewChild } from '@angular/core';
export class MyComp implement OnInit {
@ViewChild(Chips) chips: Chips;
constructor(){}
ngOnInit(){}
onKeyDown(event) {
if (event.key === ";") {
// use the internal method to set the new value
this.chips.writeValue([...this.chips.value, event.target.value]) // don't push the new value inside the array, create a new reference
this.chips.cd.detectChanges(); // use internal change detection
event.preventDefault(); //prevent ';' to be written
event.target.value = ""; // reset the input value
}
}
}
my-comp.component.html
<p-chips (keydown)="onKeyDown($event)"></p-chips>
然后可以使用[(ngmodel)]
或formcontrolname
(以表格形式)获取所有值。