Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

98
Views
How to implement abstract class with abstract method in Angular

I have a perhaps trivial question, but I cannot understand how I can use the methods of an abstract class based only on calling it and choosing the correct override based on the type of value I have as Input.

For example, if I have something like this:

export abstract class Parent {
    constructor(
        public type: View
    ){}

    abstract getSource(): string | string[]
}

export class Child1 extends Parent {
    getSource(): string {
        return this.type.view1
    }
}

export class Child2 extends Parent {
    getSource(): string[] {
        return this.type.view2
    }
}

And I wanted to call the abstract class Parent, and, based on the type, figure out whether to use the function in the Child1 or Child2 class. I thought you could do it like this:

export class AngularComponent {
    public _VieweSource: string | string[];
    @Input() set data(type: View) { 
        // here i need to return Child1.getSource() or Child2.getSource()
        // not calling new Child1(type).getSource()
        // but something like this: Parent(type).getSource() --> Child1 if type.view1=string || Child2 if type.view2=string[]
    }
}

the View type are this:

{type: "simple", view1: "hello world"} || {type: "complex", view2:["hello", "world"]}

Sorry if the question is wrong, if there are any questions I can answer. Thanks in advance.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The problem is that you are trying to choose which class to use, based on the values in type. You should not try to let inheritance figure out which class to choose, a simple if statement is build for that.

export class AngularComponent {
    public _VieweSource: string | string[];
    @Input() set data(type: View) { 
        let obj: Parent;
        if (type.view1 && typeof type.view1 === 'string'){
            obj = new Child1(type);
        } else if(type.view2 && type.view2 instanceof Array){
            obj = new Child2(type);
        }
        obj.getSource();
    }
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!