I'm trying to have inputs with a regex requirement in a ngFor loop but am not seeing the error message as expected when I put something that doesn't match the required pattern.
"Test" is never hidden and <div *ngIf="id?.hasError('pattern')">
never shows, even when I enter the wrong pattern. I can see that the input fails because I'm using Material Design and the color of the line underlining the input changes to red but I do not see any changes in regards to the error messages.
Here is my code at the moment:
(The keys pipe I have is a custom pipe because item is an object made of objects, so that breaks down the contained objects into key/value pairs.)
<div *ngFor="let item of items | keys">
<md-input-container>
<input
mdInput
placeholder={{item.placeholder}}
name={{item.name}}
pattern="\d{7}"
[(ngModel)]="item.currentValue"
#id="ngModel"
>
</md-input-container>
<div
[hidden]="id?.valid || id?.pristine"
>
<p>Test</p>
<div *ngIf="id?.hasError('pattern')">
Pattern should be xxxxxxx
</div>
</div>
</div>
尝试将name={{item.name}}
更改为name="id"
。
Try it in next way:
<div *ngFor="let item of items | keys">
<md-input-container>
<input
mdInput
placeholder={{item.placeholder}}
name={{item.name}}
pattern="\d{7}"
[(ngModel)]="item.currentValue"
#id="ngModel"
>
</md-input-container>
<div [hidden]="!displayValid(id)">
<p>Test</p>
Pattern should be xxxxxxx
</div>
</div>
And this fun in .ts file of component:
displayValid(inputRef: any): boolean {
let errors: any = inputRef.errors;
return errors && errors.pattern;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.