简体   繁体   中英

Angular2/4. Can I bind a function to ngModel?

I am using ngbDatePicker from the ng-bootstrap. I am trying to set a default date which is returned from an API. This doesn't seem to work as either i get errors or the browser freezes. The code snippet looks like this

<input class="form-control" placeholder="dd-mm-yyyy" name="from" [ngModel]="formatDate(filter.nodes[0])" (ngModelChange)="filter.nodes[0] = updateDate($event)" ngbDatepicker #d1="ngbDatepicker">

filter.nodes[0] is the date value that is returned from the API as a string. I need to format this into a JS Object for it to bind to the input.

You may use (ngModelChange)="yourMethod($event)" to bind ngModel to a method

<input label="Choose a year" (ngModelChange)="selectYearGraph($event)" [(ngModel)]="chosenYearDate" ></input>

then in your ts file

yourMethod($event){
//do your stuff
}

If you are getting data from API , then don't use dot notation. Because while loading DOM you don't have 'node' property in 'filter' variable. So try using filter['node'][0] and additionally you can also check that input field will show after loading data from API. In your case, you can try this.

<input *ngIf="filter['nodes'] && filter['nodes'][0]" class="form-control" placeholder="dd-mm-yyyy" name="from" [ngModel]="formatDate(filter['nodes'][0])" (ngModelChange)="filter['nodes'][0] = updateDate($event)" ngbDatepicker #d1="ngbDatepicker">

Let me know is it working or not.

You can use a variable to update the ngmodel and change the modal in the function

<input class="form-control" placeholder="dd-mm-yyyy" name="from" [ngModel]="dateData" (change)="updateDate($event)" ngbDatepicker #d1="ngbDatepicker">

In Ts file:-

dateData:any;
 ngOnit(){
  //call the api and write below on success response block
  this.dateData = this.formatDate(this.filter.nodes[0]);
  // Sets the initial date value
 }
  updateDate($event){
  //update your date here
     let date = logictoGetDate($event);
     this.dateData=this.formatDate(date); //
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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