Skip to content
Advertisement

ERROR TypeError: Cannot read property ‘nativeElement’ of undefined after modal popup loading in angular

i have a component with modal popup and defined a viewchild elementRef to try to get an element of input text after the modal popup opens. The modal is opened after click a button and there is a search button in the modal triggers a function in typescript but when click the button i got a warning ‘nativeElement’ of undefined. I read some questions in stack and other web sites but i didnt find a solution for this and still get same undefined error.

ts:

export class CheckoutAddressComponent implements OnInit {  
  @Input() checkoutForm: FormGroup;
  @ViewChild('search') searchTerm: ElementRef;
}

html:

<div class="form-inline">
<input (keyup.enter)="onSearch()" class="form-control mr-2" #search style="width: 300px" placeholder="Ara" type="text">
<button (click)="onSearch()" class="btn btn-outline-primary my-2">Search</button>
<button (click)="onReset()" class="btn btn-outline-success ml-2 my-2">Reset Filter</button>
</div>

ts functions :

onSearch() {
    const params = this.accountService.getCustomerParams();
    params.search = this.searchTerm.nativeElement.value;
    params.pageNumber = 1;;
    this.getCustomers();
  }


onReset() {
    this.searchTerm.nativeElement.value = '';
    this.customerParams = new CustomerParams();
    this.getCustomers();
  }

Advertisement

Answer

why do u need ViewChild ? You can use ngModel

<div class="form-inline">
<input (keyup.enter)="onSearch()" class="form-control mr-2" [(ngModel)]="searchTerm" style="width: 300px" placeholder="Ara" type="text">
<button (click)="onSearch()" class="btn btn-outline-primary my-2">Search</button>
<button (click)="onReset()" class="btn btn-outline-success ml-2 my-2">Reset Filter</button>
</div>

in component

searchTerm: string="";

onSearch() {
    const params = this.accountService.getCustomerParams();
    params.search = this.searchTerm;
    params.pageNumber = 1;;
    this.getCustomers();
  }


onReset() {
    this.searchTerm= '';
    this.customerParams = new CustomerParams();
    this.getCustomers();
  }
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement