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

时间:2019-06-12 08:25:16

标签: angular decorator angular-components html-input

我正在使用角型@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>

2 个答案:

答案 0 :(得分:1)

您需要将''添加到绑定中,否则日期选择器将假定您正在传递对象,而不是字符串。像这样:[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>

答案 1 :(得分:0)

您需要将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;
}