繁体   English   中英

角度 2/4。 我可以将函数绑定到 ngModel 吗?

[英]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.

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