Matrix vs Query, the advantage of matrix parameters

·

2 min read

In Angular you can choose to use matrix parameters. While the name sounds a lot more inspiring than the more common query parameters, matrix parameters also have one feature that makes them better.

The first time I saw matrix parameters was in Angular. And I liked what I saw, not only did the name sound better, they also looked better. They used to be the default in the early versions of Angular, and looking at the official tutorial, both matrix and query parameters are presented. Yet they are seldom used, perhaps because of a lack of knowledge about their status and features. But if you want to get the most out of your router setup, it is worth learning about matrix parameters.

Here is an easy example to get started; /search;series=Not the Nine O'Clock News. The corresponding query parameters would look like /search?series=Not the Nine O'Clock News. In this example, there is no advantage to using matrix parameters, so I would argue it is better to use the more common query parameters.

The feature that sets matrix parameters apart is that they are tied to a specific piece of the path; the URL segment where they are used. Example: /:country;map=true/:city;details=population,pollution. The map parameter is here tied to country and population & pollution to details. The query parameters are not tied to a specific part of the URL, but rather to the whole address. So there can only be one set of query params. Naturally, it is possible to work around this limitation: like /:country/:city&countrymap=1&citydetails=population,pollution. But it is a valid argument that matrix parameters make it possible to have more logical, and readable URLs.

One of the downsides with matrix parameters is that they are not handled by Google analytics, while query params are. GA will simply ignore the matrix parameters. This may have something to do with matrix parameters not being included in the HTML specification (despite the idea being presented in 1996 by Tim Berners-Lee). My impression is that this is more a bureaucratic than a practical issue and that it is safe to rely on matrix parameters. And use them when you have parameters that belong to a specific part of the path, but if not stay with the query parameters.