如何在父级中随时获取子组件输入元素

问题描述 投票:0回答:1

我正在使用父子组件。在子组件中我使用搜索框。我需要随时根据需要获取搜索框值。怎么弄这个?

子组件html - GridViewComponent

<input id="successFilter" name='filterInput' type="text" (keyup)="searchSuccess($event)">

父组件ts

@ViewChild(GridviewComponent) grdView: GridviewComponent;

在构造函数之前写了上面的行

this.grdView.filterInput.subscribe(data => {
  console.log(data);
});

我无法获得输入值

javascript angular angular5 angular-components
1个回答
1
投票

您的解决方案的一个版本是以下(组件A - 父组件,组件B - 子组件):

在组件B中:在html文件中:

<input ... [(ngModel)]="inputValue" ...>

在componentB.ts文件中:

@Input() needAnswer : ReplaySubject<any>(1);
@Output() hereYourAnswer = new EventEmmiter<any>();
inputValue: string;
private subscription: Subscription;


...

ngOnInit() {
  this.subscription = this.needAnswer.subscribe( giveMeAnswer => this.hereYourAnswer.emit(this.inputValue));
}

...
ngOnDestroy() {
  this.subscription.unsubscribe();
}

在组件A中,html:

<component-b [needAnswer]='needAnswer' (hereYourAnswer)='getAnswer(event$)'></component-b>

在componentA.ts文件中:

...
needAnswer = new ReplaySubject<any>(1);

...
getInputDataFromComponentB() {
  this.needAnswer.next('give me answer!!! please)');
}
...

getAnswer(answer) {
  console.log(answer, 'here i am');
}

...

使用RXJS很简单。

© www.soinside.com 2019 - 2024. All rights reserved.