I am creating a dynamic form by parsing a json file. So i need to bind the hidden/ngIf based on a condition. I am passing the condition from the typescript file and same thing is using in the html file. Below are my code changes
product.component.ts
export class ProductComponent implements OnInit {
condition : any;
productForm : FormGroup;
constructor(productFormBuilder : FormBuilder) {
this.productForm = productFormBuilder.group({
'name' : ["", [Validators.required, Validators.minLength(5), Validators.maxLength(10)]],
'test' :["",[]],
'middleName':["",[]],
'lastName':["",[]]
});
this.condition="!(this.productForm.get('test').value==='testing')";
}
}
product.component.html
<form [formGroup]="productForm" (submit)="onSubmit()">
<div>
<label>Name</label>
<input type="text" formControlName="name" name="name" >
<div *ngIf="productForm.controls['name'].invalid && (productForm.controls['name'].dirty || productForm.controls['name'].touched)">
<div style="color:red"
*ngIf="productForm.controls['name'].errors.required">Name is required</div>
<div style="color:red"
*ngIf="productForm.controls['name'].errors.minlength">Name is minimum of 5 characters</div>
</div>
</div>
<div>
<label>Label</label>
<input type='radio' formControlName='test' value='testing' name='test'> Testing
<input type='radio' formControlName='test' value='overflow' name='test'> Overflow
</div>
<div [hidden]= "!(this.productForm.get('test').value==='overflow')">
<label>Overflow</label>
<input type='text' formControlName='middleName' >
</div>
<div *ngIf="condition">
<div >
<label>Testing</label>
<input type='text' formControlName='lastName' >
</div>
</div>
<div [hidden]="condition">
<div >
<label>Testing</label>
<input type='text' formControlName='lastName' >
</div>
</div>
<button type="submit">Submit</button>
</form>
In my template file i had radio button with name "test", i need to show the respective div based on radio button selection. The binding is working when i place condition directly in the template file and the same thing is not working when i send it from the typescript and using the same in template file. ngIf* showing the right div when on page load but the toggling is not working.
As the form is going to create dynamically by parsing a json, I need to pass the condition from the typescript.
Can someone help me is there anything I am missing.
condition
is a non-null string value, which is a truthy value. Your *ngIf/[hidden] bindings will always be true. Bindings don't accept expressions as strings. You can probably generate a function and assign that tocondition
instead, and then invoke it from the template. - matmo