In angular2, suppose I have a Parent class and a Child1 class, they have the same properties/members and methods. How to initialize the Child1 class?
Service
@Injectable()
export class Parent {
constructor(
private currentImg: string,
private catImg: string,
private dogImg: string,
private enable: boolean) {
}
onMouseOver() {
enable = true;
currentImg = catImg;
}
onMouseClick() {
enable = false;
currentImg = dogImg;
}
}
One of the child class want to extends Parent class:
import {Parent} from "./Parent";
@Component({
selector: 'app',
templateUrl: 'app/child.html',
providers: [Parent]
})
export class Child1 {
private currentImg: string = "img/dog.png",
private catImg: string = "img/cat.png",
private dogImg: string = "img/dog.png",
private enable: false
constructor(private _parent: Parent) {
}
onMouseOver() {
this._parent.onMouseOver();
}
onMouseClick() {
this._parent.onMouseClick();
}
}
When you extend a class main class can use base class' methods and properties.
export class Base {
private image: string = "img/dog.png"; // default image
// you don't need catImg and dogImg here...
// private catImg: string;
// private dogImg: string;
private currentImg: string;
private enable: boolean;
constructor() { }
onMouseOver(image) {
enable = true;
currentImg = image;
}
onMouseClick(image) {
enable = false;
currentImg = image;
}
}
When you want to set properties in your main class, you don't initialize/set value to them in the base class. You only need to declare those properties and methods that you are using in Base class. You can set common properties that classes will share, like default image, for example.
This is how you would extend Base class in two different classes:
import {Base} from "./Base";
@Component({
selector: 'app',
template: `<button (click)="onMouseClick(image)">show cat</button>`,
providers: []
})
export class CatImage extends Base {
private image: string = "img/cat.png",
constructor() {
super();
}
}
@Component({
selector: 'app',
template: `<button (click)="onMouseClick(image)">show dog</button>`,
providers: []
})
export class DogImage extends Base {
private image: string = "img/dog.png",
constructor() {
super();
}
}
Both CatImage and DogImage will inherit enable, currentImg properties, onMouseOver() and onMouseClick() methods from Base class, and you can use them in their code/templates...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With