Search code examples
angulardecoratorangular-componentshtml-input

Angular 6 - How to set dynamic type in html input using angular input decorator


I'm passing dynamic type to input using angular @Input decorator. It's doesn't working and showing NaN value => type="NaN". How I can acheive this? Here is my code:

datepicker.html

<input  class="{{ value ? 'has-value' : '' }}"
        type="{{inputType}}"
        [(ngModel)]="value"
        [max]="getToday()"/>

datepicker.ts

@Input() inputType: string;

app.html

<app-datepicker [inputType]="datetime-local"[(ngModel)]="example1"
      (ngModelChange)="filter()"></app-datepicker>

<app-datepicker [inputType]="date"[(ngModel)]="example2"
      (ngModelChange)="filter()"></app-datepicker>

Solution

  • You need to add '' to your bindings, otherwise the datepicker assumes that you are passing an object, not a string. Like this: [inputType]="'datetime-local'"

    <app-datepicker [inputType]="'datetime-local'"[(ngModel)]="example1"
          (ngModelChange)="filter()"></app-datepicker>
    
    <app-datepicker [inputType]="'date'"[(ngModel)]="example2"
          (ngModelChange)="filter()"></app-datepicker>
    

    Alternatively, you can remove the [] from the attribute like this: Then you do not need to add the ''

    <app-datepicker inputType="datetime-local"[(ngModel)]="example1"
          (ngModelChange)="filter()"></app-datepicker>
    
    <app-datepicker inputType="date"[(ngModel)]="example2"
          (ngModelChange)="filter()"></app-datepicker>