I am getting typeError here<p *ngIf="formValue.controls['{{obj.name}}'].invalid
but when I hard code like this *ngIf="formValue.controls['uname'].invalid
it works fine.
what is the problem here?
<span *ngFor="let obj of toolData">
<span [ngSwitch]="obj.type">
<span *ngSwitchCase="'text'">
<label for="{{obj.name}}">{{obj.label}}</label>
<input type="text" id="{{obj.name}}" name="{{obj.name}}" formControlName="{{obj.name}}" value="{{obj.value}}" required="{{obj.required}}" />
<p *ngIf="formValue.controls['{{obj.name}}'].invalid && formValue.controls['{{obj.name}}'].touched" >Value required</p>
</span>
</span>
</span>
ToolData
toolData=[
{"type":"text","name":"uname","label":"User Name","value":"user name","required":true},
{"type":"number","name":"pval","label":"P val","value":"3","min":0,"max":100,"required":true},
]
CodePudding user response:
ngIf
evaluates the expression written inside that. You dont have to use string interpolation there. Use expression as below.
This jsfiddle will show a sample implementation.
It should be
*ngIf="formValue.controls[obj.name].invalid && formValue.controls[obj.name].touched"
So your template will be.
<span *ngFor="let obj of toolData">
<span [ngSwitch]="obj.type">
<span *ngSwitchCase="'text'">
<label for="{{obj.name}}">{{obj.label}}</label>
<input type="text" id="{{obj.name}}" name="{{obj.name}}" formControlName="{{obj.name}}" value="{{obj.value}}" required="{{obj.required}}" />
<p *ngIf="formValue.controls[obj.name].invalid && formValue.controls[obj.name].touched" >Value required</p>
</span>
</span>
</span>