简体   繁体   中英

Dynamically include array object variables in the HTML in Angular

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.

You are misusing prime ng p-table component, you are trying to use column headers as a input form. If you want to use the table to input new data it would be much easier to just create a <p-table> with a single row and use the built in features of primeng like the OnEditComplete() event to trigger your validation. I would also ask yourself if you really need dynamic columns? Do you need to use a table? Could you just make a form and use the validation build into prime ng?

https://www.primefaces.org/primeng/#/table/edit

https://www.primefaces.org/primeng/#/validation

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM