Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
495 views
in Technique[技术] by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...