简体   繁体   English

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

[英]@viewchild unable to get input element value from child component

I am using parent and child component. 我正在使用父级和子级组件。 In child component I use search box. 在子组件中,我使用搜索框。 I need to get search box value at any time on demand. 我需要随时按需获取搜索框值。 How to get this? 如何得到这个?

Child Component html - GridViewComponent 子组件html-GridViewComponent

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

Parent Component ts 父组件

@ViewChild(GridviewComponent) grdView: GridviewComponent;

wrote above line before constructor 在构造函数之前写在上面

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

am unable to get input value on demand 无法按需获得输入值

GridView html GridView html

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

GridView typescript 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, call getChildValue() whenever you need to get the value ParentComponent打字稿,每当需要获取值时调用getChildValue()

@ViewChild('gridView') grdView;

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

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

ParentComponent html ParentComponent html

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM