LoginSignup
4
2

More than 5 years have passed since last update.

Angular 6 で、日付や時刻との双方向データバインディング

Last updated at Posted at 2018-07-24

Angular 始めましたなので、メモ書きです。

普通のやつ

HTML

<input type="text" [(ngModel)]="myText" />
<!-- これでもおk <input type="text" [ngModel]="myText" (ngModelChange)="myText=$event" /> -->

<label>{{myText}}</label>

TypeScript

export class Main
Component {
  public myText: string = "hoge";
}

結果

Untitled5.gif

[(ngModel)]="myText"[ngModel]="myText" (ngModelChange)="myText=$event" の短縮表記に過ぎないことを知りました。

日付の <input> と 時刻の <input>Date 型プロパティ

HTML

<input type="date" 
  [ngModel]="myDate | date: 'y-MM-dd'" 
  (ngModelChange)="myDateChange($event)" />

<input type="time" 
  [ngModel]="myDate | date: 'HH:mm'" 
  (ngModelChange)="myTimeChange($event)" />

<label>{{myDate}}</label>

TypeScript

public myDate: Date = new Date(2018, 6, 20, 15, 56); // 2018/7/20 15:56

public myDateChange(text: string) {
  // インスタンス変えた方がいいと思うんだ
  const newDate = new Date(this.myDate);

  // 新しいインスタンスに年月日をコピー(時刻は維持)
  const parsed = new Date(text);
  newDate.setFullYear(
    parsed.getFullYear(),
    parsed.getMonth(),
    parsed.getDate());    

    this.myDate = newDate;
}

public myTimeChange(text: string) {
  // インスタンス変えた方がいいと思うんだ
  const newDate = new Date(this.myDate);

  // 新しいインスタンスに時刻をコピー(年月日は維持)
  const buf = text.split(':');
  if (buf.length === 2) {
    newDate.setHours(parseInt(buf[0], 10), parseInt(buf[1], 10));
    this.myDate = newDate;
  }
}

結果

Untitled6.gif

パイプ(| date:) のところの意味が未だわかってません。

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2