How to translate form errors with angular i18n? -
i working on i18n angular , provide translation form errors. not know how that. followed guide angular website. , tried use select method not working.
initially, before trying translate, had following code in component.ts:
onvaluechanged(data?: any) { if (!this.userform) { return; } const form = this.userform; (const field in this.formerrors) { // clear previous error message (if any) this.formerrors[field] = ''; const control = form.get(field); if (control && control.dirty && !control.valid) { const messages = this.validationmessages[field]; (const key in control.errors) { this.formerrors[field] += messages[key] + ' '; } } } } formerrors = { 'firstname': '' }; validationmessages = { 'firstname': { 'required': 'firstname required.', 'pattern': 'only alphabetics caracters allowed.' } }; and following code in component.html:
<div *ngif="formerrors.firstname" class="form-control-feedback alert"> {{ formerrors.firstname }} </div> it worked because there no translation. then, made following updates:
in component.ts:
validationmessages = { 'firstname': { 'required': 'required', 'pattern': 'pattern' } }; in component.html:
<div *ngif="formerrors.firstname" class="form-control-feedback alert"> <ng-container i18n="@@usermodalfirstnameerror"> {formerrors.firstname, select, required {required} pattern {pattern}} </ng-container> </div> in messages.fr.xlf file, have this:
<trans-unit id="usermodalfirstnameerror" datatype="html"> <source>{var_select, select, required {required} pattern {pattern} }</source> <target> {var_select, select, required {nom utilisateur obligatoire} pattern {pattern}} </target> ... </trans-unit> unfortunately, solution not work.
i found issue comes from. actually, there 2 mistakes.
the first 1 related 'var_select' in .xlf file. has been generated angular build command => "ng-xi18n --i18nformat=xlf". 'var_select' works if "direct" variable used (for example if put "{toto, select, required {required} pattern {pattern}}" , toto equal "required"). seems not work if variable table used (which case variable "formerrors.firstname"). replaced 'var_select' in .xlf file name of variable 'formerrors.firstname'.
the second 1 in "onvaluechanged" function:
for (const key in control.errors) { this.formerrors[field] += messages[key] + ' '; }because of space character @ end, variable did not match 1 of values defined (for example, 'required ' expected 'required'. note additional space @ end of 1st value)
Comments
Post a Comment