I have an Angular 5 project with a method named createForm
. It will basically create just a form. However, the form created changes depends on the flight inventory code. If flight inventory code id TAG_ON I will create a form omitting messagePrefixSMSValidator
and also form control named message to empty.
createForm() {
this.formGroup = this.fb.group(
{
defaultTemplate: [this.defaultInitialValue],
language: [null, Validators.required],
message: [ this.messagePrefix ? this.messagePrefix:'', [Validators.required]],
longUrl: ['']
},
{
validator: [
hasUrlTagValidator(TemplatesService.urlTag),
messagePrefixSMSValidator(this.messagePrefix? this.messagePrefix: null, 'message')
]
}
);
if(this.flight.inventory.code === FlightInventoryCode.TAG_ON) {
this.formGroup = this.fb.group(
{
defaultTemplate: [this.defaultInitialValue],
language: [null, Validators.required],
message: [ '', [Validators.required]],
longUrl: ['']
},
{
validator: [
hasUrlTagValidator(TemplatesService.urlTag),
]
}
);
}
}
Is there a way to rewrite my code so that it looks simple?
1 Answer 1
Formatting. Typically you want to use TSLint, and possible also Prettier. I've ran your code through Prettier with the standard configuration. (Note that the point is consistency and readability. It doesn't matter if you want to use
'
or"
, tabs or spaces, etc)this.messagePrefix ? this.messagePrefix : ""
can be simplified asthis.messagePrefix || ""
Looking at your code, it looks like we want to assign different values to
message
andvalidator
depending on the values ofthis.flight.inventory.code
. So lets keep everything else the same rather than having separate code paths. If we were to keep the current structure, then we should at least put the first assignment tothis.formGroup
in an else block, so we don't assign it twice.Hopefully you can see the gain in readability and terseness. It's much more clear that
message
andvalidator
(but nothing else) depends onthis.flight.inventory.code
in the codepen version.