簡體   English   中英

如何在 angular 2 中在 formcontrolname 上應用管道

[英]How to apply pipe on formcontrolname in angular 2

我有一個輸入類型文本,它使用 formControlName 顯示值。 我寫了一個管道來格式化值。 如何在 formControlName 上應用此管道(測試管道)。 我在這里讀到你不能直接在輸入類型文本上應用管道。

@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 >

您應該能夠使用雙花括號表示法來使用管道。 像這樣:

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

演示

您需要一個“模板表達式”。 來自 Angular 文檔:

模板表達式產生一個值。 Angular 執行表達式並將其分配給綁定目標的一個屬性; 目標可能是 HTML 元素、組件或指令。

{{1 + 1}}的插值大括號包圍了模板表達式1 + 1

在您的情況下,構建一個應用您的自定義管道的模板表達式:

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

您可以使用 [value]="form.controls.abc.value | testPipe" 轉換輸入值

這適用於您希望在輸入字段中顯示的只讀字段。

您仍然可以使用 formControlName="abc" 取得一些成功,這取決於您的管道如何修改 abc 中的值。

這在 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"
      /> 

使用 value 屬性設置數據以及相應的管道

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM