Imagine if you have a typescript file like the following one:
JavaScript
x
23
23
1
@Component({
2
selector: 'app-product-alerts',
3
templateUrl: './product-alerts.component.html',
4
styleUrls: ['./product-alerts.component.css']
5
})
6
export class ProductAlertsComponent {
7
8
//code ...
9
10
//code (imagine several methods) that can the isolated from the rest
11
12
calculatesAge(){
13
this.age
14
}
15
16
checkIdPermission() {
17
this.permission
18
}
19
20
//
21
22
}
23
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:
JavaScript
1
15
15
1
//Separate file:
2
import {ProductAlertsComponent} from ".product-alerts.component.ts"
3
4
export class UserOperations extends ProductAlertsComponent {
5
6
calculatesAge(){
7
this.age
8
}
9
10
checkIdPermission() {
11
this.permission
12
}
13
}
14
15
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?
Advertisement
Answer
Notice that the template is defined in the @Component decorator, not in the class itself. Therefore reusing the template is as simple as
JavaScript
1
8
1
@Component({
2
selector: 'app-product-alerts',
3
templateUrl: './product-alerts.component.html',
4
styleUrls: ['./product-alerts.component.css']
5
})
6
export class ProductAlertsComponent {
7
// definition here
8
JavaScript
1
10
10
1
@Component({
2
selector: 'app-user-operations',
3
templateUrl: '../product-alerts/product-alerts.component.html',
4
styleUrls: ['./product-alerts/product-alerts.component.css']
5
})
6
export class UserOperations extends ProductAlertsComponent {
7
thatOneMethodThatIsOverwritten(): void {
8
}
9
}
10