Search code examples
angulartypescriptangular-materialangular-ngmodel

Angular2 - Input-Value undefined


I want to pass the Input-Value to the function by clicking the Button.

<md-card> 
     <md-input-container><input mdInput ngDefaultControl [ngModel]="newInput">
     </md-input-container> 
     <button md-raised-button (click)="newInputValue(newInput)">Update</button>
</md-card>

But the value of newInput in the function newInputValue(..) is always undefined.


Solution

  • In the below link you are using property binding(one way), so you cannot access the variable in the DOM

     <md-input-container><input mdInput ngDefaultControl [ngModel]="newInput">
    

    Change the [ngModel] to [(ngModel)]

    Alternatively,

     <div class="button-row">
      <md-input-container><input mdInput #inputVal [ngModel]="newInput">
         </md-input-container> 
         <button md-raised-button (click)="newInputValue(inputVal.value)">Update</button>
      </div>
    

    In the above case you will have the value in your method, so your one way databinding remains untouched

    LIVE DEMO of second option