【问题标题】:Angular 6 - How to set dynamic type in html input using angular input decoratorAngular 6 - 如何使用角度输入装饰器在 html 输入中设置动态类型
【发布时间】:2019-10-26 16:51:38
【问题描述】:

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

【问题讨论】:

    标签: angular decorator angular-components html-input


    【解决方案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>
    

    【讨论】:

      【解决方案2】:

      你需要将type绑定到一个变量

      ChildComponent.html

      <input [type]='type'>
      

      子组件.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;
      }
      

      【讨论】:

        猜你喜欢
        • 2018-02-04
        • 2021-10-23
        • 2018-03-31
        • 2017-04-06
        • 2022-11-27
        • 1970-01-01
        • 1970-01-01
        • 2021-09-30
        • 2020-07-08
        相关资源
        最近更新 更多