0

I have a function and it's being used in different components. To use it across few components, i am pasting the same code in each component. I want to create a lib, in which i will write this method and then import it across the components. Please suggest a way how to approach.

@Component({
  // Some metadata 
})
export class ComA  {
   dataValid(val: any): string {
       // some login
    }
}   



@Component({
  // Some metadata 
})
export class ComB  {
   dataValid(val: any): string {
       // some login
    }
}

Here i am using dataValid() function repeatedly.

I want some thig like

@Component({
  // Some metadata 
})
export class ComA extends GenericLib {

}   



@Component({
  // Some metadata 
})
export class ComB extends GenericLib {

}

And use dataValid() function in GenericLib class

Vaibhav
  • 771
  • 2
  • 11
  • 23
  • What's the problem? What have you tried? Components are also in libraries. Put your code in a `*.ts` file. prefix declarations (classes, variables, functions) with `export` (like you did with the components) and then import and use it wherever you please. – Günter Zöchbauer Jan 26 '17 at 13:19
  • I am using follwing code :- @Component({}) export class GenericLib implements OnInit { dataValid(val: any): string { // some login } } and getting following error : --- No template specified for component GenericLib – Vaibhav Jan 26 '17 at 13:27
  • Sounds about right. `@Component({})` should be `@Component({selector: 'xxx', template: '
    my template here
    })`
    – Günter Zöchbauer Jan 26 '17 at 13:31
  • That's fine but since I am creating a lib for reusing my methods there is no need for creating a template in the selector. – Vaibhav Jan 26 '17 at 13:35
  • Quite confused what you think a "lib" is. What are you planning to do with it? – Günter Zöchbauer Jan 26 '17 at 13:36
  • My aim is to place the reusable method in a class and extend it in others class. So that if I want to modify the method I do not have to go to each class, just modify it at one place . Did you get it ? – Vaibhav Jan 26 '17 at 13:40
  • The problem is then related to components and inheritance, but not to library. See for example https://scotch.io/tutorials/component-inheritance-in-angular-2, http://stackoverflow.com/questions/36475626/how-to-extend-inherit-angular2-component, https://medium.com/@amcdnl/inheritance-in-angular2-components-206a167fc259#.5moevmjsr – Günter Zöchbauer Jan 26 '17 at 13:47
  • Thanks URL helped a lot !! – Vaibhav Jan 27 '17 at 03:08

0 Answers0