我有一个文本区域列表:
text-area.component.html
<!--suppress HtmlFormInputWithoutLabel -->
<textarea [ngClass]="generateTextAreaClass()" (keypress)="onKeyPress($event)">{{ value }}</textarea>
textarea 有一个keypress事件。
当我在其中一个文本区域中按下一个键时,它会触发keypress该组件的所有实例的事件。
结果,我触发了 5 个事件。这显然不代表我刚刚作为用户所做的操作。
{textareaSelector: ".app-utility-textarea-1-1", keypressType: "shift+enter"}
{textareaSelector: ".app-utility-textarea-1-1", keypressType: "shift+enter"}
{textareaSelector: ".app-utility-textarea-1-1", keypressType: "shift+enter"}
{textareaSelector: ".app-utility-textarea-1-1", keypressType: "shift+enter"}
{textareaSelector: ".app-utility-textarea-1-1", keypressType: "shift+enter"}
如何将事件限制为仅针对我当前正在输入的文本区域触发,以便仅触发一个事件?
@Component({
selector: 'app-utility-textarea',
templateUrl: './text-area.component.html',
styleUrls: ['./text-area.component.scss']
})
export class TextAreaComponent implements AfterViewInit {
constructor(private eventBus: EventBusService) {
}
@Input() value: string;
@Input() id: string;
public textAreaClassPrefix = 'app-utility-textarea';
...
generateTextAreaClass(): string {
return `${this.textAreaClassPrefix}-${this.id}`;
}
onKeyPress(event: KeyboardEvent) {
event.stopPropagation();
if (event.key === 'Enter' && event.shiftKey) {
event.preventDefault();
const textAreaKeyPressEvent: TextAreaKeyPressEvent = {
textareaSelector: this.generateTextAreaClassCSSSelector(),
keypressType: TextAreaKeyPressType.SHIFT_ENTER
};
this.eventBus.textAreaKeyPressSubject$.next(textAreaKeyPressEvent);
}
}
}
事件总线.service.ts
@Injectable()
export class EventBusService {
public navbarSubject$ = new BehaviorSubject(DashboardNavbarEvent.SIDEBAR_MENU_CLOSED);
public textAreaKeyPressSubject$ = new Subject<TextAreaKeyPressEvent>();
constructor() {
}
}
订阅者.component.ts
@Component({
selector: 'app-subscriber',
templateUrl: './subscriber.component.html',
styleUrls: ['./subscriber.component.scss']
})
export class SubscriberComponent implements OnInit {
@Input() public block: any;
@Input() public index: number;
constructor(private eventBus: EventBusService) {
}
ngOnInit() {
this.eventBus.textAreaKeyPressSubject$.subscribe((event: TextAreaKeyPressEvent) => {
console.log(event);
});
}
}