【问题标题】:Angular2 pipe not working for inputAngular2管道不适用于输入
【发布时间】:2016-09-30 09:46:13
【问题描述】:

我在我的 HTML 中使用 angular2 内置管道百分比

<input class="ibox1 rightalign" type="text" [ngModel]="_note.StudentPercent| percent:'.5-5'" ngControl="StudentPercent" pattern="^[0-9]\d*(\.\d+)?$" #StudentPercent="ngForm">

它的工作和向输入框显示正确的数据,但是当我更改字段管道的值时不起作用。

如何解决?

【问题讨论】:

    标签: html angular typescript pipe


    【解决方案1】:

    您已在更改_note.StudentPercent 输入时重新应用您的模型值过滤器。您也可以使用 ngModelChange 处理程序。

    <input class="ibox1 rightalign" type="text" 
       [ngModel]="_note.StudentPercent| percent:'.5-5'" 
       (ngModelChange)="changeToPercent(_note.StudentPercent,'.5-5')" 
       ngControl="StudentPercent" pattern="^[0-9]\d*(\.\d+)?$"
       #StudentPercent="ngForm" />
    

    代码

    changeToPercent(percent, format){
       //make sure PercentPipe in declarations & providers of NgModule
       this._note.StudentPercent = new PercentPipe().transform(percent, format)
    }
    

    【讨论】:

    • 遇到异常:动作表达式中不能有管道。
    • @srashtisj 我猜你不能直接在事件动作上使用Pipes,基本上你需要调用组件的方法并在组件内部做这件事并分配回模型,如(ngModelChange)="_note.StudentPercent = doApplyPipe(_note.StudentPercent)" & where @ 987654327@将返回结果
    • 是的!但是如果我使用这种方法,我必须在保存时转换值。比如 0.24 => 24.00000% 然后在节省 24.00000% => 0.24000 的同时......还有其他使用管道的方法吗?
    • @srashtisj 看到一般管道已被用于根据模型值显示其他内容,您并没有真正改变实际模型值,显然您对其进行了调整。
    猜你喜欢
    • 1970-01-01
    • 2016-12-30
    • 1970-01-01
    • 2016-12-13
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 2012-07-09
    • 1970-01-01
    相关资源
    最近更新 更多