Issue
I am new to the Angular 6. Here is my problem.
In the Component:
ngOnInit() {
this.cols = [
{ field: 'col1', header: 'Column 1', filterMatchMode: 'contains' },
{ field: 'col2', header: 'Column 2', filterMatchMode: 'contains' },
...
];
this.selectedColumns = this.cols;
}
In the HTML:
<p-table [columns]="selectedColumns" >
<th *ngFor="let col of columns;">
<div [ngClass]="{'has-error': col.field.invalid && col.field.touched }">
<input [(ngModel)]="newRecord[col.field]" name="{{col.field}}" #{{col.field}}="ngModel" required type="text" pInputText [style]="{'width':'100%'}" class="form-control form-control-sm search-input" pattern="[0-9]+" />
</div>
<div *ngIf="col.field.invalid && col.field.touched" class="td-error-msg">
Valid input is required.
</div>
</th>
</p-table>
I am getting issue where when I try to check and insert the dynamic value "col.field" in the ngIf and Angular id.
1. *ngIf="col.field.invalid && col.field.touched"
2. name="{{col.field}}" #{{col.field}}="ngModel"
I am trying to provide validation for the input field with error message.
Solution
You can create a template variable with a static name, such as #field
(or whatever name you like), and since it is scoped to the item, there will be no naming conflicts.
<input [(ngModel)]="newRecord[col.field]" name="{{col.field}}" #field="ngModel"... />
...
<div *ngIf="field.invalid && field.touched" class="td-error-msg">
Valid input is required.
</div>
field
will always refer to the input of the current item. The *ngFor
structural directive creates a template for each item, each with its own scope. This should be the easiest solution over dynamically creating template variable names.
https://stackblitz.com/edit/angular-mefkxp?file=src%2Fapp%2Fapp.component.html
Answered By - Wingnod
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.