MEAN Angular Routing and Forms 2 — Questions and Answers
Question 1: In Angular template-driven forms, which directive does Angular automatically apply to all <form> elements?
- [ngFormGroup]
- formControl
- ngForm (Correct answer)
- templateForm
Correct answer: ngForm
Angular automatically applies the ngForm directive to all <form> elements, creating an NgForm instance that tracks the form's validity, value, and submission state.
Question 2: Which directive creates two-way data binding between a form input and a component property in template-driven forms?
- [(ngBind)]
- [(ngModel)] (Correct answer)
- [formControl]
- [ngValue]
Correct answer: [(ngModel)]
[(ngModel)] uses the banana-in-a-box syntax to create two-way data binding, synchronizing the input element value with the component property in both directions.
Question 3: What CSS class does Angular add to a form control that fails validation?
- ng-error
- ng-invalid-touched
- ng-dirty
- ng-invalid (Correct answer)
Correct answer: ng-invalid
Angular adds the ng-invalid class to any form control that fails validation, regardless of whether the user has interacted with it.
Question 4: How do you enable the built-in 'required' validator on an input field in a template-driven Angular form?
- [required]="true"
- ngRequired
- required (Correct answer)
- validate="required"
Correct answer: required
Adding the standard HTML5 'required' attribute to an input that also has ngModel activates Angular's built-in required validator.
Question 5: How do you create a template reference variable that holds the NgForm directive instance for validity checks?
- #myForm="angular"
- #myForm="ngFormRef"
- #myForm="ngForm" (Correct answer)
- [#myForm]="ngForm"
Correct answer: #myForm="ngForm"
Using #myForm="ngForm" exports the NgForm directive instance into the template variable, enabling expressions like myForm.valid or myForm.submitted.
Question 6: Which Angular class represents the overall state and aggregate value of a template-driven form?
- NgFormControl
- NgModel
- FormGroup
- NgForm (Correct answer)
Correct answer: NgForm
NgForm is the directive Angular creates for each template-driven <form> element, providing access to the form's collective validity, value, and submitted state.
Question 7: Which event binding on a <form> element should you use to handle template-driven form submission in Angular?
- (click) on the submit button
- (submit) on the form element
- (ngSubmit) on the form element (Correct answer)
- (formSubmit) on the form element
Correct answer: (ngSubmit) on the form element
(ngSubmit) is the Angular-specific event emitted when a template-driven form is submitted, and it prevents the default browser form submission behavior.
In Angular template-driven forms, which directive does Angular automatically apply to all elements?