Suppose we first check whether a resource is not loading like this:
@if (!countriesResource.isLoading()) {
<ul>
@for (
country of countriesResource.value();
track country.name.official
) {
<li>{{ country.name.official }}</li>
}
</ul>
If the resource is not loading, however has not initiated a request yet, is there a way to provide an initial value so that countriesResource.value()
resolves to an initial value?
2
Answers
Today no.
But keep in mind that
resource
is an experimental API and the Angular team plan to have an RFC on the concept ofresource
in the following week.Yes, you can provide an initial value for countriesResource.value() when the resource hasn’t initiated a request yet. This is typically achieved by setting a default value for the resource before the request is made. Here’s how you can structure your logic depending on your framework or implementation:
Example with Default Value
Assume countriesResource supports a way to set an initial value, such as countriesResource.value or a similar method:
Now your rendering logic remains safe because the initial value guarantees
If the resource doesn’t natively support an initialValue or you cannot modify the resource directly, you can introduce a fallback value dynamically:
And modify your conditional rendering:
}
Summary
Providing an initial value ensures that your UI doesn’t break while waiting for data. Most resource-handling libraries or frameworks provide mechanisms for setting an initial state (initialValue, defaultValue, etc.) or allow you to handle it programmatically using fallbacks.