masalibの日記

システム開発、運用と猫の写真ブログです

Angular:インプットイベント

Angular(バージョン2以降)の勉強、その12です
前回でクリックイベントができたので
今回はインプットイベントになります
formの部分で使うので大事です

template側(/app/servers/servers.component.html)

<label>Server Nmae </label>
<input type="text" class="form-control" (input)="onUpdateServerName($event)">
  <p>{{serverName}}</p>

<button class="btn btn-primary" [disabled]="!allowNewServer" (click)="onCreateServer()">追加するよ</button>
<p>{{serverCreationStatus}}</p>
<p>{{ allowNewServer}}</p>
<p [innertext]="allowNewServer"></p>

追加したのは

<input type="text" class="form-control"  (input)="onUpdateServerName($event)">
<p>{{serverName}}</p>

inputタグとそれにインプットのバイディング(input)の部分になります
serverNameはインプットした内容を反映する部分になります
f:id:masalib:20170506200332p:plain

TypeScript側(/app/servers/servers.component.ts)親子関係の親の部分です

export class ServersComponent implements OnInit {
  allowNewServer  = false;
  serverCreationStatus = "No Server was created";
  serverName = "";
  constructor() {
    setTimeout(() =>{
      this.allowNewServer = true;
    },3000);
  }
  ngOnInit() { }

  onCreateServer(){
    this.serverCreationStatus ='Server was created'
  }
  onUpdateServerName(event: any){
    console.log(event)
    this.serverName = (<htmlinputelement>event.target).value;
  }
}

追加したのが「onUpdateServerNameの部分になります」
コンソールログは普通のjavascriptのログになります

f:id:masalib:20170506201143p:plain

結果

入力した内容がしたのserverNameの変数部分に反映されています
またそのイベントがコンソールログに記録されています

f:id:masalib:20170506201337p:plain

コンソールログのeventログの
→ target
→ value
に入力した「test」があります

f:id:masalib:20170506201356p:plain


(input)="onUpdateServerName($event)"
と記載している部分は
[(ngModel)]="serverName"
と記載して直接いれることが可能
フィルターとかやりたい場合は関数の方がいいかも


Angular 2: From Theory To Practice (English Edition)

Angular 2: From Theory To Practice (English Edition)

Angular 2 The Complete Guide

Angular 2 The Complete Guide

次はngIfについてです
masalib.hatenablog.com


ちなみに講義の10%が終わった・・・
あと何日かかるのやら