Wednesday, September 30, 2020

Typescript polymorphism for Angular component

Angular project may have several components that have some shared methods and properties. It is better to create a common base component and then extends it to to other sub components. The base component has an empty html template and css style, and only contain typescript code.

Both base component and sub components need to be added into module declaration section.

The injected constructor parameter needs to be passed from subclass constructor to base class constructor as constructor parameters with public access.

Similar to Java, typescript uses runtime binding when deciding which method to be invoked, it does not matter what is the current variable type, instead it will invoke the instance object's last method implemented by the inheritance tree. If the subclass does not implement the method, then it goes up to find the implementation from its parent class.

When a method in base class calls another method, it will invoke the implementation of the subclass. The only way to invoke the parent class' method is using super.certainFunc().

Sample code:


class animal {
  public name: string;
  constructor(n) {
    this.name = n;
  }
  public makeSound() {
    console.log(this.name);
  }

  public run() {
    this.makeSound();
    console.log('animal run');
  }
}

class dog extends animal {
   constructor(dn){
     super(dn);
   }
   public makeSound() {
     console.log('dog call. ' + name);
   }

   public run() {
    this.makeSound();
    super.makeSound();
    super.run();
    console.log('dog run');
  }
}

call the method from a button event handler:
  onTempTest2() {
   const d = new dog('pa');
   d.makeSound();
   d.run();
   const a: animal = d;
   a.makeSound();
   a.run();

  }

 

1 comment:

  1. As we have strict policies ensuring the delivery of original and highest quality product to our valued clients in Anatomy Assignment Writing. Customer satisfaction is the greatest award for us.

    ReplyDelete