Enjoy 20% off all plans by following us on social media. Check out other promotions!

Mortgage Calculator Solution

Author
Senior Staff Engineer, Google
Languages
HTMLJS

Solution

This question evaluates whether you understand how to allow users to enter form inputs, validate them and perform calculations based on the inputs.

We will divide our app into 2 components AppComponent and FormComponent.

FormComponent will be responsible for accepting user input and passing it to AppComponent.

FormComponent

To collect user data, we use a <form> element and <input> fields.

To validate input, use the built-in input type validators (<input type="number">) and NgForm to mark calculation button disabled if the form is invalid. You can use the required attribute in HTML to ensure that all input fields are filled out and the min attribute to ensure that input fields have a valid minimum value before the submit event callback is fired.

Use ngModel in your template you can set initial values to the input fields.

AppComponent

After computing the 3 necessary amounts using the formula, use Intl.NumberFormat() to format the amounts to 2 d.p. with a dollar symbol. Feel free to customize the formatting to your own locale and currency.

State

In AppComponent we will store the state of the mortgage, that is updated by events from FormComponent.

Models

export interface FormState {
loanAmount: number;
interestRate: number;
loanTerm: number;
}
export interface FormState {
loanAmount: number;
interestRate: number;
loanTerm: number;
}

Angular Insights

  • You can adopt a more advanced, reactive-like approach using reactive forms.

  • You might create service for maintaining the state. Inject the service in smart component and crete dumb components that only display and interact with the UI and all events from dumb components are passed to the smart one.

  • If you're confident with the latest Angular version, consider using signals standalone API.

Test Cases

  • Basic case
    • Enter a loan amount, interest rate, and loan term for a simple mortgage scenario, and verify that the monthly mortgage payment and total amount paid are calculated correctly. For example, a 30-year mortgage on a $100,000 loan at 3% interest rate should result in a monthly payment of $421.60, a total amount paid of $151,777.45, and total interest of $51,777.45.
  • Invalid inputs
    • Leave the loan amount field blank and submit. Expect to see an error message prompting the user to fill out the field.
    • Try to enter text instead of numeric characters in any of the fields. <input type="number"> should prevent non-numeric characters from being entered.

Accessibility

  • Use a <label> for the form fields to indicate what the <input> is for. You can nest <input> within <label> to make the association implicit.
  • Add aria-live="polite" to the results container element to announce content changes to users of assistive technologies.