This method will be used by the controller to retrieve the form selections.
Add the definition of the method as follows:
getChartFormDetails(): { error?: string; countryId?: string; indicator?: string; fromYear?: number; toYear?: number, chartType?: string } { // Continue here }
As stated before, notice the return type again. We reuse the same trick as in the previous chapter, by defining a custom type including an optional error. Then, we check the different form fields and report back to the user when something is invalid.
Inside that method, we need to add some validation logic:
if (this._chartConfigurationForm.checkValidity() === false) { this._chartConfigurationForm.reportValidity(); return { error: "The chart configuration form is invalid!" } } // we check the validity of specific form fields if (this._countrySelect.checkValidity() === false) { this._countrySelect.reportValidity(); return { error: "A country must be selected!" } } if (this._indicatorSelect.checkValidity() === false) { this._indicatorSelect.reportValidity(); return { error: "An indicator must be selected!" } } if (this._fromYearSelect.checkValidity() === false) { this._fromYearSelect.reportValidity(); return { error: "A start year must be selected!" } } if (this._toYearSelect.checkValidity() === false) { this._toYearSelect.reportValidity(); return { error: "An end year must be selected!" } } if (this._chartTypeSelect.checkValidity() === false) { this._chartTypeSelect.reportValidity(); return { error: "A chart type must be selected!" } }
Finally, we can create the return value if all validation tests have passed successfully:
const countryId: string = this._countrySelect.value; const indicator: string = this._indicatorSelect.value; const fromYear = Number.parseInt(this._fromYearSelect.value); const toYear = Number.parseInt(this._toYearSelect.value); const chartType: string = this._chartTypeSelect.value; return { countryId, indicator, fromYear, toYear, chartType };
When the form is fully validated, we return our custom object. For the definition of that object, we have used the property shorthand notation introduced by ES2015. It allows us to write countryId, for example, instead of countryId: countryId. You can learn more about that feature here: http://es6-features.org/#PropertyShorthand.