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

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

我有一个带有模式弹出窗口的组件,并定义了一个 viewchild elementRef 以尝试在模式弹出窗口打开后获取输入文本的元素。单击一个按钮后打开模态,模态中有一个搜索按钮触发打字稿中的一个函数,但是当单击该按钮时,我收到未定义的警告 'nativeElement'。我在堆栈和其他网站上阅读了一些问题,但我没有找到解决方案,但仍然遇到相同的未定义错误。

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 函数:

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();
  }

为什么需要 ViewChild?你可以使用 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>

在组件中

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();
  }