Home > Software engineering >  Previous variable value in Angular
Previous variable value in Angular

Time:04-07

I'm coming from React and trying to get a grasp on both Vue and Angular.

In React if I need to use the previous value of a variable I can create a simple lifecycle hook like this one:

import { useRef, useEffect } from "react";

export const usePrevious = (value) => {
    const ref = useRef();

    useEffect(() => {
        ref.current = value;
    }, [value]);

    return ref.current;
};

and then use it on variable:

const [currentValue, setCurrentValue] = useState("")
const previousValue = usePrevious(currentValue);

useEffect(() => {
 if (currentValue.length === 0 && previousValue?.length === WORD_LENGTH) {
    // something
 } else {
    setCurrentValue(previousValue)
 }
},[currentValue]);

In Vue it's pretty much the same:

import { ref, watch } from "vue";

export const usePrevious = (value) => {
  const previous = ref();

  watch(value, (_, oldValue) => {
    previous.value = oldValue;
  });

  return previous;
};

and then use it on variable:

const currentValue = ref("");

const previousValue = usePrevious(currentValue);

watch(previousValue, () => {
 if (currentValue.value.length === 0 && previousValue?.value.length === WORD_LENGTH) {
    // something
 } else {
    currentValue.value === previousValue.value
 }
})


So my question is: how do I do something like that in Angular? How would I get the previous value from Observable and use it later on in a different function?

CodePudding user response:

I do not know for what scenario you are trying to extract the previous value. In Angular, there are life cycle methods and ngOnChanges life cycle method is triggered whenever there is a change in the value of the component input.

you could explore this method in case you're trying to track the component input previous values.

CodePudding user response:

If you want to get the previous value of a variable from observable you can use the pairwise() operator of rxjs.

You can refer to the below link for more details. https://www.learnrxjs.io/learn-rxjs/operators/combination/pairwise

  • Related