[英]Angular2/4. Can I bind a function to ngModel?
我正在使用 ng-bootstrap 中的 ngbDatePicker。 我正在嘗試設置從 API 返回的默認日期。 這似乎不起作用,因為我收到錯誤或瀏覽器凍結。 代碼片段看起來像這樣
<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] 是從 API 以字符串形式返回的日期值。 我需要將它格式化為一個 JS 對象,以便它綁定到輸入。
您可以使用(ngModelChange)="yourMethod($event)"
將 ngModel 綁定到一個方法
<input label="Choose a year" (ngModelChange)="selectYearGraph($event)" [(ngModel)]="chosenYearDate" ></input>
然后在你的 ts 文件中
yourMethod($event){
//do your stuff
}
如果您從 API 獲取數據,則不要使用點表示法。 因為在加載 DOM 時,'filter' 變量中沒有 'node' 屬性。 因此,請嘗試使用 filter['node'][0] ,此外您還可以檢查從 API 加載數據后是否會顯示輸入字段。 在你的情況下,你可以試試這個。
<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">
讓我知道它是否有效。
您可以使用變量來更新 ngmodel 並更改函數中的模態
<input class="form-control" placeholder="dd-mm-yyyy" name="from" [ngModel]="dateData" (change)="updateDate($event)" ngbDatepicker #d1="ngbDatepicker">
在 Ts 文件中:-
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); //
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.