Member-only story

Angular — Four old fashioned practices that you should NOT carry forward to Angular

Liu Ting Chun
5 min readFeb 4, 2021

--

Before the invention of modern JS frameworks, most websites were built with static HTML plus classic JS libraries, such as jQuery. Many practices have been formulated based on this stack, but some of them may no longer applicable with modern frameworks nowadays. Here I have summarized four classic web development practices that are not suitable anymore for Angular.

1. Manipulating instances

Element selector plays an important role in classic web development. When we want to perform action on an element, we use the selector to get the corresponding instance and manipulate the instance directly. Selecting and manipulating instances is a common and the preferred way of doing things in classic websites. Yet, direct instance manipulation (with features like @ViewChild), such as calling a public component method, reading some component attributes, etc., is a less preferred approach in Angular. The reason is we cannot ensure the reactivity when doing such manipulations. For example:

@Component({
selector: 'custom-button',
...
})
export class CustomButtonComponent {
activated = false;
public setActivated(value: boolean) {
this.activated = value;
}
}

We need to run setActivated manually every time we know when there is change in the state:

@Component(...)
export class TestPageComponent {
activated = false;
@ViewChild('customButton1') customButton1: CustomButtonComponent;
@ViewChild('customButton2') customButton2: CustomButtonComponent;
onDataLoad() {
this.activated = !!this.data.length;
this.customButton1.setActivated(this.activated);
this.customButton2.setActivated(this.activated);
}

...
}

We are managing the reactivity ourselves here. It is risky as it means a defect if new codes break the assignment chain, which is very common. States are not automatically reacted to change, which is the major problem. To avoid this issue, we can simply utilize the official @Input binding and @Output events.

@Component({
selector: 'custom-button',
...
})
export class CustomButtonComponent {
@Input activated = false;
}

--

--

Liu Ting Chun
Liu Ting Chun

Written by Liu Ting Chun

Web developer from Hong Kong. Most interested in Angular and Vue. Currently working on a Nuxt.js + NestJS project.

No responses yet

Write a response