angulardynamicfactoryemit

run function in dynamic component when a function is executed in parent angular


I need to execute a function when a function in the parent component of dynamically created component is executed without changing the parent component.

Do you have any idea for me how to tell in child to execute a function when the function is run in the parent?


Solution

    1. You can override the function of de parent (if the function is public) if inject the parent in child(*)

      If you has in parent a function

        doSomething()
        {
          console.log("I am parent")
        }
      

      In your child you write

        constructor(@Optional() @Host() parent: ParentComponent) {
          parent.doSomething = () => {
            console.log("I am parent") //make the same of the parent
      
            console.log('I am child'); //and make something more
          };
        }
      

      see a stackblitz

    2. Another is make the same using a directive

    3. Or extend the parentComponent creating a new Component that extends from Parent

    (*)Really I don't suggest this approach, but if you can not "touch" the parent I can not imagine another way