如何将angular2-json-schema-form中array类型添加按钮文本改为德语?
修改angular2-json-schema-form数组添加按钮文本为德语
我之前也用这个库做过Angular 4的表单开发,刚好知道怎么调整这个按钮的文本,给你几个实用的方案,你可以根据自己的需求选:
方案1:通过自定义消息配置快速修改(推荐)
这个库本身支持通过messages属性覆盖默认的提示文本,针对数组添加按钮的话,只需要覆盖addItem这一项就行,而且它支持占位符{0}来自动替换数组的名称,完美匹配你的需求。
步骤:
- 在你的组件类里定义自定义消息对象:
// 组件的.ts文件 import { Component } from '@angular/core'; @Component({ selector: 'app-your-form', templateUrl: './your-form.component.html' }) export class YourFormComponent { yourSchema = /* 你的JSON Schema */; yourForm: any[] = []; // 表单模型 // 自定义德语消息 customMessages = { addItem: 'Zu {0} hinzufügen' }; }
- 在模板里把这个消息对象传给
json-schema-form组件:
<!-- 组件的.html文件 --> <json-schema-form [schema]="yourSchema" [form]="yourForm" [messages]="customMessages" ></json-schema-form>
这样所有数组的添加按钮都会自动显示德语文本,而且{0}会自动替换成对应数组的名称,和原功能保持一致。
方案2:自定义数组组件(适合需要深度定制样式/结构的场景)
如果除了文本,你还想修改按钮的样式或者数组的整体布局,可以自定义一个数组组件来替换默认的实现:
步骤:
- 创建自定义数组组件:
// custom-array.component.ts import { Component, Input } from '@angular/core'; import { WidgetComponent } from 'angular2-json-schema-form'; @Component({ selector: 'app-custom-array', templateUrl: './custom-array.component.html' }) export class CustomArrayComponent extends WidgetComponent { @Input() arrayTitle: string; // 获取数组的名称 }
- 编写自定义模板(重点修改按钮文本):
<!-- custom-array.component.html --> <div class="array-widget"> <!-- 保留原数组的其他渲染逻辑,这里只展示按钮部分 --> <button type="button" class="btn btn-default" (click)="addItem()" > Zu {{ arrayTitle }} hinzufügen </button> </div>
- 在你的模块里注册这个组件(Angular 4需要添加到
entryComponents):
// app.module.ts import { NgModule } from '@angular/core'; import { JsonSchemaFormModule } from 'angular2-json-schema-form'; import { CustomArrayComponent } from './custom-array.component'; @NgModule({ declarations: [CustomArrayComponent], entryComponents: [CustomArrayComponent], // Angular 4必须加这个 imports: [JsonSchemaFormModule] }) export class AppModule { }
- 在表单组件里配置使用自定义组件:
// 你的表单组件.ts schemaFormOptions = { widgets: { array: CustomArrayComponent // 指定数组用自定义组件渲染 } };
- 模板里传入配置:
<json-schema-form [schema]="yourSchema" [form]="yourForm" [options]="schemaFormOptions" ></json-schema-form>
方案3:全局配置(所有表单统一用德语)
如果你的整个应用都需要用德语显示这些按钮文本,可以在根模块里全局配置:
// app.module.ts import { NgModule } from '@angular/core'; import { JsonSchemaFormModule } from 'angular2-json-schema-form'; @NgModule({ imports: [ JsonSchemaFormModule.forRoot({ messages: { addItem: 'Zu {0} hinzufügen' } }) ] }) export class AppModule { }
这样所有的json-schema-form组件都会默认使用德语的添加按钮文本,不用每个表单单独配置。
内容的提问来源于stack exchange,提问作者Snake
相关产品推荐
相关产品推荐

