Home > Net >  Angular - How to link several typescript files with one template file?
Angular - How to link several typescript files with one template file?

Time:08-08

Imagine if you have a typescript file like the following one:


@Component({
  selector: 'app-product-alerts',
  templateUrl: './product-alerts.component.html',
  styleUrls: ['./product-alerts.component.css']
})
export class ProductAlertsComponent {

//code ...

//code (imagine several methods) that can the isolated from the rest

 calculatesAge(){
  this.age ...
 }

 checkIdPermission() {
  this.permission ...
 }

//

}

I would like to outsource these methods. However, the classes must inherit the properties from ProductAlertsComponent, as it would operate on/with them. So, in a separate file, I would do the following logic:

//Separate file:
import {ProductAlertsComponent} from ".product-alerts.component.ts"

export class UserOperations extends ProductAlertsComponent {

 calculatesAge(){
  this.age ...
 }

 checkIdPermission() {
  this.permission ...
 }
}

But the template angular file (product-alerts.component.html) would not recognize calculatesAge() and checkIdPermission(). How could I solve it? It is not maintainable to have a ProductAlertsComponent class with several methods that could grow after years of developing. How could I link the extended class with the template angular file?

CodePudding user response:

Notice that the template is defined in the @Component decorator, not in the class itself. Therefore reusing the template is as simple as

@Component({
  selector: 'app-product-alerts',
  templateUrl: './product-alerts.component.html',
  styleUrls: ['./product-alerts.component.css']
})
export class ProductAlertsComponent {
// definition here
@Component({
  selector: 'app-user-operations',
  templateUrl: '../product-alerts/product-alerts.component.html',
  styleUrls: ['./product-alerts/product-alerts.component.css']
})
export class UserOperations extends ProductAlertsComponent {
    thatOneMethodThatIsOverwritten(): void {
    }
}

CodePudding user response:

You can import those typescript file and use those methods like below

Import your typescript here.

@ViewChild('mytypescript') public mytypescript: ProductAlertsComponent;

Use the methods like this

this.mytypescript.calculatesAge();
  • Related