@viewchild无法从子组件获取输入元素值

时间:2018-03-06 18:36:26

标签: javascript angular angular-components viewchild

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

子组件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);
});

无法按需获取输入值

1 个答案:

答案 0 :(得分:2)

GridView html

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

GridView打字稿

import { Output, OnInit } from '@angular/core';

@Component({
  selector: 'app-gridView',
  templateUrl: './gridView.component.html',
  styleUrls: ['./gridView.component.scss']
})
export class GridViewComponent implements OnInit {
  @Output() sendValue = new EventEmitter<string>();
   filterInput = '';

   constructor(){}

   ngOnInit() {}

  getValue() {
      this.sendValue.emit(this.filterInput);
  }
}

ParentComponent typescript,每当需要获取值

时调用getChildValue()
@ViewChild('gridView') grdView;

getChildValue() {
   this.grdView.getValue();
}

receivedValue(theValue: string) {
   //this is where you actually get theValue
}

ParentComponent html

<app-gridView #gridView (sendValue)="receivedValue($event)"></app-gridView>