【问题标题】:How to apply pipe on formcontrolname in angular 2如何在 Angular 2 中的 formcontrolname 上应用管道
【发布时间】:2018-11-18 16:07:18
【问题描述】:

我有一个输入类型文本,它使用 formControlName 显示值。我写了一个管道来格式化值。 如何在 formControlName 上应用此管道(测试管道)。我读过here,您不能直接在输入类型文本上应用管道。

@Pipe({ name: 'testPipe' })
export class TestPipe implements PipeTransform {
public transform(value: string): string {
   //some logic
    return value;

  }
}

如何应用此管道

<input tabindex="1" type="text" class="form-control-style" 
formControlName="abc" id="abc" name="abc" 
readonly >

【问题讨论】:

    标签: angular input pipe


    【解决方案1】:

    您应该能够使用双花括号表示法来使用管道。像这样:

    <input tabindex="1" type="text" class="form-control-style" 
      formControlName="{{'abc' | testPipe}}" id="abc" name="abc" readonly >
    

    Demo

    【讨论】:

    • 我添加了一个演示供您查看。
    • 这不起作用,你没有使用name1作为formControlName Demo link @TeddySterne
    • @Chenna 该演示适用于我。我看到三个表单输入是基于前缀name 和后缀123 基于ngFor 中的值绑定的。
    【解决方案2】:

    您需要一个“模板表达式”。来自 Angular 文档:

    模板表达式产生一个值。 Angular 执行 表达式并将其分配给绑定目标的属性;这 目标可能是 HTML 元素、组件或指令。

    {{1 + 1}} 中的插值大括号围绕着模板表达式 1 + 1

    在您的情况下,构建一个应用您的自定义管道的模板表达式:

    <input tabindex="1" type="text" class="form-control-style" formControlName="{{'abc' | testPipe}}" id="abc" name="abc" readonly >
    

    【讨论】:

    • 我想我知道它为什么不起作用,当我的表单加载时,我没有为该文本输入设置值。只有在某些操作之后,该值才会被设置。我们如何才能阻止这个管道在没有价值的情况下执行。我试图检查未定义的,仍然中断
    • 管道应用在formControlName上,而不是输入文本值上,所以我认为它与它无关。您应该随时拥有一个有效的 formControlName 值,它不能为空、未定义或引用某些不存在的 fomControl。您能否显示有关错误的更多详细信息或更多代码?谢谢!
    • 假设我更改为这个 formControlName="{{'abc' | testPipe}}" 并且当我将 console.log 放入转换方法时,它只在表单加载时执行一次,当单击 btn 时,文本输入会获得一些值,我没有看到转换被调用
    【解决方案3】:

    您可以使用 [value]="form.controls.abc.value | testPipe" 转换输入值

    这适用于您希望在输入字段中显示的只读字段。

    您仍然可以成功使用 formControlName="abc",具体取决于您的管道如何修改 abc 中的值。

    【讨论】:

      【解决方案4】:

      这在 angular 8 上效果很好,对于带有管道的表单组 formControlName:

      短:

            [value]="form.get('my_form_group_field').value | MyPipe"
      

      更长:

            <input
             [readonly]="isEditMode"
             formControlName="my_form_group_field" 
             matInput
             type="text"
             [value]="form.get('my_form_group_field').value | MyPipe"
            /> 
      

      【讨论】:

        【解决方案5】:

        使用 value 属性设置数据以及相应的管道

        <input type="text" matInput placeholder="Created Date" 
        formControlName="createdDate" 
        [value]="myForm.get('createdDate').value | date">
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-07-29
          • 1970-01-01
          • 2016-09-20
          • 1970-01-01
          • 2016-08-17
          • 1970-01-01
          • 2017-03-13
          • 2017-02-01
          相关资源
          最近更新 更多