【问题标题】:Angular - Select control not reacting to changesAngular - 选择控件不响应更改
【发布时间】:2021-08-06 19:39:27
【问题描述】:

我有一个选择输入,应该以 15 分钟为单位显示时间值,但不知何故我无法选择任何值。这是代码:

<select matNativeControl [(ngModel)]="selectedTime" >                
    <option *ngFor="let time of getAvailableTimeValues()" [ngValue]="time|date:'shortTime'">{{time | date:'shortTime'}}</option>
</select>

在这种情况下,selectedTime 模型是一个字符串。我已经尝试了几种变体,结果相同。必须是本机选择控件,否则浏览器会因那么多值而崩溃。当我使用 (change) 事件时,它总是显示默认的初始值,而不是被选中的值。

我知道选择时间有不同的控件,但它们不允许阻止任意间隔。

有什么建议吗?

【问题讨论】:

    标签: angular select time drop-down-menu angular11


    【解决方案1】:

    请查看getAvailableTimeValues() 方法返回的值的类型。

    如果您返回具有相同字符串的数组或命名数组,您的代码将选择一个值,但如果您返回匿名对象数组,则不会。

    @Component({
      selector: 'select-form-example',
      templateUrl: 'select-form-example.html'
    })
    export class SelectFormExample {
    
      selectedTime: string;
      timeValues: any[] = [new Date(1621286945378), new Date()];
    
      getAvailableTimeValues() {
        /*This works since we are pointing to the same memory location via our variable and 
         the same values are drawn after each change detection cycle.*/
        return this.timeValues;
    
        /*This will work since strings are primitives. Again the same values are drawn 
         after each change detection cycle.*/
        //return [new Date(1621286945378).toISOString(), '1621287945379'];
    
        /*This will not work since Date is a reference type that changes on each change 
        detection cycle. The view is being re-drawn after each change detection cycle and
        we are losing the reference to the value we just clicked.*/
        //return [new Date(1621286945378), new Date()];
      }
    }
    

    【讨论】:

      【解决方案2】:

      你好试试下面的代码

      <select matNativeControl [(value)]="selectedTime" >                
          <option *ngFor="let time of getAvailableTimeValues()" [ngValue]="time|date:'shortTime'">{{time | date:'shortTime'}}</option>
      </select>
      

      value 指令适用于 &lt;mat-select&gt;&lt;/mat-select&gt;

      【讨论】:

        猜你喜欢
        • 2023-03-15
        • 2019-06-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-14
        • 2016-01-03
        • 1970-01-01
        • 2023-04-07
        相关资源
        最近更新 更多