emit keydown.enter事件在child中



我正试图发出一个"keydown.enter";从中的父组件转换为子组件。我做不到。请指导我如何做到这一点。

ParentComponent.html

<form [formGroup]='parentForm'>
<div>
<input type='search' placeholder="search (keydown.enter)="search($event)">
</div>
<app-child (keydown.enter)="search()" [childForm]="parentForm.controls.childForm"> 
</app-child>
</form>

ChildComponent.ts

@Output() keydown.enter = new EventEmitter(); // keydown.enter does not work
ngAfterViewInit() {
// something like.. 
this.keydown.enter.emit({ 
// keydown.enter does not work
});
}

keydown.enter在typescript或javascript 中不是有效的标识符

我已经复制了你的代码

//child component
@HostListener('document:keydown.enter', ['$event']) onKeydownHandler(event: KeyboardEvent) {
this.keydownEnter.emit(event)

}
@Output() keydownEnter = new EventEmitter();


//parent component html
<app-child (keydownEnter)="Search()" ></app-child>



// parent component 
Search() {
console.log("event")
}

首先,我认为您的ChildComponent中需要一个@Input,而不是@Output。ChildComponent正在侦听某种事件,而不是发出它。

然后我会做一些类似的事情

ParentComponent.html

<form [formGroup]='parentForm'>
<div>
<input type="search" placeholder="search" (keydown.enter)="_search$.next($event.target.value)">
</div>
<app-child [search]="search$" [childForm]="parentForm.controls.childForm"> 
</app-child>
</form>

ParentComponent.ts

public _search$ = new Subject();
public search$ = this._search$.asObservable();

ChildComponent.ts

@Input() search: Observable<string>;

ngOnInit() {
this.search.subscribe(val => 
// Do Something with searched input
);
}

您可以尝试使用一些Subject和Symbol作为更新子组件的触发器

父组件:

class ParentComponent {
reloadSubject: BehaviorSubject<symbol> = new BehaviorSubject(Symbol(''));
search() {
// your code...
this.reloadSubject.next(Symbol(''));
}  
}
<form [formGroup]='parentForm'>
<div>
<input type='search' placeholder="search" (keydown.enter)="search($event)">
</div>
<app-child [reload] = "reloadSubject | async" [childForm] = "parentForm.controls.childForm"> </app-child>
</form>

子组件:

@Input() set reload(data: symbol) {
// here you can run some logic for your child component...
}

相关内容

最新更新