網站搜尋

typescript - 如何在 HTML 中使用變數的 pipe?Angular 9


我正在將整個管道作為其中一個參數傳遞,但我很難使用它。
物件的格式如下:

{
    column: 'productExpirationDate', 
    caption: 'Product expiration date', 
    pipe: 'date: \"' + PIPE_DATE_FORMAT + '\"' 
},

當 PIPE_DATE_FORMAT 儲存 'yyyy-MM-dd' 時,輸出格式應該是 'date: "yyyy-MM-dd"'
,如果我嘗試在 html 文件中使用它,像這樣

<span *ngIf="element.pipe">{{ row[element.column] | element.pipe }}</span>

它大喊著

解析器錯誤:意外的標記 ''.'' ...

我找到了 Angular - 傳遞管道作為變數的文章,但我無法弄清楚如何在我的情況下使其工作。此外,該答案中使用的 get 方法已被棄用,這只會增加更多的困惑。

我如何能從變數使用那個管道?

答案#1

自訂管道呢?你可以直接在你的管道中實現這個參數邏輯,而你的 HTML 看起來會像這樣:

<span *ngIf="element.pipe">{{ row[element.column] | myCustomPipe: element.customPipeParams }}</span>

你應該做的就是正確地實作 myCustomPipe,當然你可以重複使用現有的 Angular pipes,例如日期 pipe。

答案#2

在這裡,你使用管道的方式不太正確。首先,你的管道文件應該包含如下所示的代碼:

@Pipe({
    name: 'customDate'
})
export class CustomDateFormat extends DatePipe implements PipeTransform {
    transform(value: any, args?: string): any {
        let formatter;
        switch (args) {
            case 'PIPE_DATE_FORMAT ':
                {
                    formatter = super.transform(value, 'yyyy-MM-dd');
                    break;
                }
        
                
            default:
                {
                    formatter = super.transform(value, 'dd/mm');
                    break;
                }
        }
        return formatter;
    }
}

而你的變數應該有這些值:

{
  column: 'productExpirationDate', 
  caption: 'Product expiration date', 
  pipe: 'customDate: PIPE_DATE_FORMAT ' 
},

而你的 HTML 應該被替換為:

<span *ngIf="element.pipe">{{ row[element.column] | element.pipe }}</span>