Angular Tips
Global Styles
Other than adding styles to src/styles.css
, we can also load any other CSS
files by listing them in the angular.json
file. We should add them to the
projects.{project-name}.architect.build.options.styles
array. This way, we can
apply Bootstrap or some other framework styling.
By the way, the forementioned src/styles.css
is also listed there. That’s how
it gets loaded.
References to HTML Elements
We can mark any HTML element with a reference to be able to access it easily from somewhere else.
Here’s an example:
We’re able to pass a reference to a <p>
element when clicking a button.
@ViewChild
Building on top the defined HTML element reference, we can add this to our component’s TypeScript code:
Encapsulated Styles
Styles of comonents are encapsulated and they are applied ONLY to the component to which the styles are attached. This is a cool feature that is missing from Vue.js (Angular has to better at something!) By default, Angular does it in an “Emulated” way by attaching custom attributes to HTML elements that belong to the component and by modifying the styles’ selectors to narrow down the scope of the style. There’s also a way to do it via Shadow DOM, but that’s not supported by some of the browsers.
Renderer2
It is recommended to use Renderer2
to access DOM elements instead of doing it
via references. This is safer in environments
such as Service Worker, server or mobile.
We can inject it into our classes and use as follows:
Moving Events to Services
Normally, our components would emit events, and a parent of the component can react to that. The problem appears when the component that wants to get some event is not a direct parent of it. Then, we have to move the event up (and sometimes down) the component tree to connect the two ends. It’s cumbersome.
One solution is to:
- move the
EventEmitter<T>
to a service; - replace that
EventEmitter<T>
withSubject<T>
- it works pretty much the same, but is more functional (read here).EventEmitter<T>
would still work if for some reason we want to keep using that.
Then, both the even producer and consumer inject that service. The producer can raise the event via the service:
The consumer(s) can subscribe to it:
Disabling a button for invalid forms
Here’s an easy way to disable a button if a form is not valid:
Environments
Angular has built-in support for switching config values between DEV and PROD
environments. Any app initialized by the CLI has the src/environments
directory where two files exist:
environment.ts
- for DEVenvironment.prod.ts
- for PROD
During the build, Angular CLI will attach one of them to the bundle. When we
build with ng build
, the PROD one will be used.
Inside of the environment files we can put all the config values we need. Then,
we import the environment
object wherever we need to use these configs.
What if there should be more envs than two?