NG Interview Set I - Forms Questions Flashcards
NG Interview Set I - Forms Questions
1
Q
When do you use template driven vs model driven forms? Why?
A
- Template driven forms make more sense for simpler forms, at least in terms of validation
- Model driven or Reactive forms lend themselves to easier testing of the validation logic, so if that’s complex, Reactive forms make more sense
- There’s also the issue of asynchronous (template driven forms) vs. synchronous (model driven)
2
Q
How do you submit a form?
A
- use the ngSubmit event binding like so:
< form (ngSubmit)=" onSubmit()" ... >
3
Q
What’s the difference between NgForm, FormGroup, and FormControl? How do they work together?
A
- FormGroup tracks the value and validity state of a group of AbstractControl instances
- FormControl does the same for an individual control
- NgForm is a directive that Angular automatically attaches to each < form > tag
- It has its own ‘valid’ property which is true only if every contained control is valid
4
Q
What’s the advantage of using FormBuilder?
A
- Reduces repetition and clutter by handling details of control creation for you
5
Q
How do you add form validation to a form built with FormBuilder?
A
- pass in Validator objects along with the FormControl objects…
6
Q
What’s the difference between dirty, touched, and pristine on a form element?
A
- Dirty means it contains user data, touched means the user has at least done something with a particular control (perhaps just literally ‘touched’ it by giving it focus?), and pristine means the control has not been touched at all by the user
7
Q
How can you access validation errors in the template to display error messages?
A
- Use formErrors
8
Q
What is async validation and how is it done?
A
- Verifying some field using some asynchronous call (perhaps a server call) … return a Promise < ValidationResult > from your validator. When creating a FormControl object, you can pass an asynchronous validator into the constructor (e.g. new FormControl(‘value’, syncValidator, asyncValidator))
9
Q
What is patchValue used for?
A
- Setting a form value (one or more fields with an object) bypassing validation