Angular 6 - 如何使用 angular 输入装饰器在 html 输入中设置动态类型

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

我正在使用 angular @Input 装饰器将动态类型传递给输入。它不起作用并显示 NaN 值 => type="NaN"。我怎样才能做到这一点?这是我的代码:

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>

您需要将 '' 添加到您的绑定中,否则日期选择器会假定您传递的是一个对象,而不是字符串。像这样:[inputType]="'datetime-local'"

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

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

或者,您可以像这样从属性中删除 []: 那么你不需要添加 ''

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

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

您需要将 type 绑定到

中的变量

ChildComponent.html

<input [type]='type'>

ChildComponent.ts

@Input() type;

App.component.html

<select (change)='change($event)'>
  <option>number</option>
  <option>date</option>
  <option>datetime-local</option>
</select>

<app-child [type]='type'></app-child>

{{type}}

App.component.ts

type;
change(ev ) {
 this.type = event.target.value;
}