Reputation: 4118
I am not able to bind variable from component as a pattern with Angular 4. This code works:
<textarea #sss="ngModel"
class="form-control"
id="sss"
maxlength="350"
pattern="[a-zA-Z '-,;.]*"
[(ngModel)]="formModel.sss" name="sss"></textarea>
But when I try to add something like:
export class SssComponent {
public sssPattern: string = "[a-zA-Z '-,;.]*";
and add it like that:
<textarea #sss="ngModel"
class="form-control"
id="sss"
maxlength="350"
pattern="sssPattern"
[(ngModel)]="formModel.sss" name="sss"></textarea>
it don't. Also tried variations like:
[pattern]="sssPattern"
[pattern]={{sssPattern}}
pattern={{sssPattern}}
with no success. Angular 4
Upvotes: 3
Views: 12806
Reputation: 71931
You have to use attr.pattern
, because pattern is an attribute with no reflection from a property:
<textarea [attr.pattern]="sssPattern"></textarea>
Interpolation and property binding can set only properties, not attributes.
You need attribute bindings to create and bind to such attributes.
Attribute binding syntax resembles property binding. Instead of an element property between brackets, start with the prefix
attr
, followed by a dot (.) and the name of the attribute. You then set the attribute value, using an expression that resolves to a string.
You cannot use pattern
on a textarea
. Angular does have its own PatternValidator
, which means all that nonsense I said about attr
does not hold up for this specific case, but I believe this does not work on a textarea, because textarea
itself does not contain the pattern
attribute in standard HTML5
, as opposed to the input
element.
In order to use a pattern on a textarea
, you should create a CustomValidator
Upvotes: 3
Reputation: 2736
If you use Angular Forms, below code can be used for field and pattern validation
let emailFormat = "[A-Za-z0-9._%-]+@[A-Za-z0-9._%-]+\\.[a-z]{2,3}";
let nameFormat = "[a-zA-Z\s]+$";
this.name = new FormControl("", Validators.compose([Validators.required, Validators.pattern(nameFormat)]));
this.email = new FormControl("", Validators.compose([Validators.required, Validators.pattern(emailFormat)]));
Upvotes: 2