How to get the name or instance of the child component in patent component in angular?

56 Views Asked by At

Suppose I have three components: P1, C1, and C2.

When constructor or Child C1 get called with super we call the constructor of parent P1 component similarly for C2 child, now I want to know from which child (C1/C2) the parent constructor get called.

How to get the name or instance of the child component in patent component in angular?

1

There are 1 best solutions below

0
On BEST ANSWER

Parent class can be inherited by components C1 and C2 by using the extends keyword.

When this is done the properties and methods are inherited by the child.

When two classes/components inherit a single class P1 Then that means there are two separate scopes of P1 inherited by the children, each component has its own set of properties/methods from the parent and changes are both completely isolated from each other.

During inheritance, its mandatory to call the super() inside the constructor of the children. This is required to call the constructor of the parent. In angular, you can use this super, to pass the dependency injection properties like router, activatedRoute to the parent, so that the parent methods have access to them.

This is a great method for core reusability/sharing between multiple components!

Method 1

Parent

export class A {
   fromWhichChild: string  = '';
}

Child B

export class B extends A{
   fromWhichChild: string  = '';

   constructor() {
       this.fromWhichChild = 'B';
       super();
   }
}

Child C

export class C extends A{
   fromWhichChild: string  = '';

   constructor() {
       this.fromWhichChild = 'C';
       super();
   }
}

Method 2

Parent

export class A {
   fromWhichChild: string  = '';

   constructor(fromWhichChild: string) {
       this.fromWhichChild = fromWhichChild;
   }
}

Children can do

export class C extends A{

   constructor() {
       super('C');
   }
}