How to pass values and functions from a Child component to a Parent using a ref in Angular ,2024

In this article, we will learn about How to pass values and functions from a Child component to a Parent using a ref in Angular

Solution 1: pass values and functions from a Child component to a Parent using a ref in Angular

Source: dev.to

// Parent Component
const App = () => {
  const ref = useRef();

  return (
    <div>
      <ComponentWithButton ref={ref} />
      <button onClick={() => ref.current.increment()}>another button</button>
    </div>
  );
};

// Child Component
const ComponentWithButton = forwardRef((props, ref) => {
  useImperativeHandle(ref, () => ({increment}))

  const [count, setCount] = useState(0);
  const increment = () => setCount(count + 1);
  return (
    <div>
      <button onClick={increment}>click</button>
      <h2>Count: {count}</h2>
    </div>
  )
})

Discover more from STRUGGLER KING.COM

Subscribe now to keep reading and get access to the full archive.

Continue Reading