Thursday, 29 October 2020

Angular NameOf in Component for String Safe and NgOnchanges

What is the best way to compare NgOnChanges, while making it String Type safe in Angular? Currently this is what I am doing.

NgOnChanges SimpleChanges variable is datatype : any and accepts any variable name, even if misspelled. Trying to find clean way to prevent this.

Original:

else if (changes?.product?.previousValue != changes?.product?.currentValue) {
    this.submitSearch();

New:

export const nameof = <T>(name: keyof T) => name;

public readonly productMember = nameof<WebStoreSearchComponent>("product");

if ((changes[this.productMember]?.previousValue == null || changes[this.productMember]?.previousValue?.length === 0) {
    this.submitSearch();

Does Angular have any native way to conduct this?

Resources:

https://schneidenbach.gitbooks.io/typescript-cookbook/content/nameof-operator.html



from Angular NameOf in Component for String Safe and NgOnchanges

No comments:

Post a Comment