Search code examples
htmlangularinputangular-template

Input field of type number is not showing default values (in angular)


I have the following code in stock-status.component.ts file

@Component({
  selector: 'app-stock-status',
  template:`
  <input type="number" value='0' min='0' required [(ngModel)]='updatedStockValue'/>
  <button class="btn btn-primary" [style.background]='color' (click)='stockValueChanged()'>Change Stock Value</button>
    
  `,
  styleUrls: ['./stock-status.component.css']
})

As you can see in the image it is not showing the default value as 0 enter image description here

And whenever I click the Button when no data is initialized , it shows NaN which is not what I want

Any Kind of Help and Guidance would be appreciated


Solution

  • The ngModel binding might have precedence here. You could ignore the value attribute and set updatedStockValue in it's definition.

    Try the following

    @Component({
      selector: 'app-stock-status',
      template:`
      <input type="number" min="0" required [(ngModel)]="updatedStockValue"/>
      <button class="btn btn-primary" [style.background]="color" (click)="stockValueChanged()">Change Stock Value</button>
        
      `,
      styleUrls: ['./stock-status.component.css']
    })
    export class AppComponent {
      updatedStockValue: number = 0;
      ...
    }