Using Computed Property Names in Angular
Computed property names can come in handy when you have complicated properties

In most Angular projects, you will find that form property keys are not enclosed in quotes, simply because Typescript and or JavaScript allow for this.
For example, to create a form with two input elements, you will have two properties accordingly and the component code would look like this :
export class ProfileEditorComponent {
profileForm = new FormGroup({
firstName: new FormControl(‘’),
lastName: new FormControl(‘’),
});
}
Note that the firstName
and lastName
property keys are not quoted and this works just fine. The aforementioned property keys could have equally been enclosed in quotes and this would also work.
At this point you might be wondering, why then would I ever want to enclose my property keys in quotes if they work just fine without them? You are right, but in some cases, you just have to use quotes on your property key(s).
What would you do if you had a property that had some strange character in it? For example, a vertical bar or pipe character.Take this property key, for example: firstName|Suffix
. In this case, you just have to use quotes on your property key, and the code would look like this:
export class ProfileEditorComponent {
profileForm = new FormGroup({
‘firstName|Suffix’: new FormControl(‘’),
lastName: new FormControl(‘’),
});
}
Taking this further, let’s say you wanted the property key lastName
to be dynamic, that is, to have a value that changes. This is where ES6 computed property Names comes in handy.
Starting with ES6 (ECMAScript 2015), you can use computed property names within object initializer syntax. This allows for property names to be placed in square brackets.
Updating the above code with a computed property name, on the last property key, would look like this:
export class ProfileEditorComponent {
public endName= ‘computedLastName’; profileForm = new FormGroup({
‘firstName|Suffix’: new FormControl(‘’),
[this.endName]: new FormControl(‘’),
});
}
We now have the property key [this.endName]
which is equal to computedLastName
. This property key may now have a dynamic value by initializing or updating it via the endName
variable.
You can even do complex computations with computed property names, but we will leave it here for now. Good luck and Happy coding 😃!