Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

99
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda