Conditionally Displaying Form Fields with ngIf
Demonstrate ways to conditionally display form fields based on other field values, using Angular's ngIf directive to create a dynamic user experience.
import { Component } from '@angular/core';
@Component({
selector: 'app-dynamic-form',
template: `
<form>
<label for="showMore">Show more options:</label>
<input type="checkbox" id="showMore" [(ngModel)]="showMore" name="showMore" />
<div *ngIf="showMore">
<label for="additionalField">Additional Field</label>
<input type="text" id="additionalField" name="additionalField" />
</div>
</form>
`,
})
export class DynamicFormComponent {
showMore: boolean = false;
}
This Angular component defines a form with a checkbox to toggle the visibility of an additional text input field. The `*ngIf` directive is used to conditionally display the additional form field based on the value of the `showMore` property, which is bound to the checkbox.