Introducing ngOnChanges()

The ngOnChanges() method is nothing less than another life cycle hook that will trigger each time Angular sets a data-bound input property. We had to use it instead of the constructor or ngOnInit() methods for a rather obvious reason: we can't load the questions unless the parent quiz property is available, so we need to postpone the Http call until the parent component sets it. Since the quiz is also retrieved with an asynchronous Http call by the parent component, we had to find a way to tell our QuestionListComponent when the data-bound property is actually updated.

The following schema should help you better visualize the issue:

The rounded rectangle with gray background is the asynchronous thread where the QuizEditComponent retrieves the quiz using the HttpClient.

By looking at the upper portion of the preceding schema, we can see how, without using ngOnChanges(), the QuestionListComponent will issue a completely useless Http call trying to get the questions of an empty quiz object, thus getting zero results. Besides, when the quiz is actually retrieved, it won't do anything because there are no triggers that can tell that the quiz object value has been changed; long story short, we will never get these questions.

The lower portion of the schema tells a whole different story: there are no useless Http calls at the end of the constructor-based life cycle, as the isFirstChange() method that we put within our ngOnChanges() implementation will return TRUE, giving us a good reason to ignore the event and do nothing. Later on, when the parent's async call will complete and the quiz will be set, that same method will return FALSE, giving the green flag for issuing the Http call the right way--or, rather, at the right time.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.54.136