【问题标题】:Use pipe in an input attribute在输入属性中使用管道
【发布时间】:2018-02-21 06:18:49
【问题描述】:

我正在使用 UI 框架:SmartAdmin

这提供了i18n 的国际化功能

我正在尝试在这个 Boostrap 验证模块中使用它。

如果我放这个,它就可以工作了:

 <input type="text" class="form-control" name="firstname" data-bv-notempty="true" 
 data-bv-notempty-message="The first name is required and cannot be empty"
 data-bv-stringlength-max="50" data-bv-stringlength-message="The first name must be less than 50 characters long"/>

但我尝试使用管道:

<input type="text" class="form-control" name="firstname" data-bv-notempty="true" 
data-bv-notempty-message="{{'The first name is required and cannot be empty' | i18n}}"
data-bv-stringlength-max="50" data-bv-stringlength-message="The first name must be less than 50 characters long" />

我得到这个错误:

无法绑定到“data-bv-notempty-message”,因为它不是已知的 “输入”的属性。 ("ut type="text" class="form-control" 名称=“名字”数据-bv-notempty=“真” [ERROR ->][data-bv-notempty-message]="'名字是必需的' | i18n" data-bv-stri"): ng:///UserModule/UserAccountComponent.html@66:22

问题:如何在输入属性中使用管道?

编辑:添加代码管道:

import { Pipe, PipeTransform } from '@angular/core';
import {I18nService} from "./i18n.service";

@Pipe({
  name: 'i18n',
  pure: false
})
export class I18nPipe implements PipeTransform {

  constructor(public i18nService: I18nService){}

  transform(phrase: any, args?: any): any {
    //console.log(phrase)
    return this.i18nService.getTranslation(phrase);
  }

}

方法:getTranslation()

public getTranslation(phrase:string):string {
    return this.data && this.data[phrase] ? this.data[phrase] : phrase;
}

【问题讨论】:

  • 请使用angularJs标签。 Angular 标签适用于 Angular 2+ :-)
  • @alexKhymenko 它被正确标记了。它是有角度的 2+ 问题
  • @Portekoi 抱歉,只是角度 2 中的绑定不同。假设是angular.js。
  • 你能试试[attr.data-bv-notempty-message]="'The first name is required and cannot be empty' | i18n"吗??
  • @PankajParkar 没有错误但管道没有运行

标签: angular


【解决方案1】:

它会抛出一个错误,因为 Angular 不理解该属性名称。要允许自定义属性在角度上下文之外起作用,您可以考虑添加 CUSTOM_ELEMENTS_SCHEMA 元素,该元素将用于 HTML 上的任何其他自定义属性。

import { CommonModule } from '@angular/common';

@NgModule({
  declarations: [ ... ],
  exports: [ ... ],
  imports: [ ... ],
  schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
})
export class AppModule {}

你也可以使用属性绑定,比如[attr.something]="value"

[attr.data-bv-notempty-message]="'The first name is required and cannot be empty' | i18n"

【讨论】:

    猜你喜欢
    • 2017-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-23
    • 1970-01-01
    • 2019-02-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多