Issue
I have an Angular component with two input properties. I would like to call a method when both properties are set, is there any event I can use?
export class ProductComponent implements OnInit {
_product: Product;
@Input() set product(value: Product) {
_product = value;
}
_attributeType: any;
@Input() set attributeType(value: any) {
_attributeType = value;
this.doSomeWorkWhenBothProductAndAttributeTypeAreSet();
}
doSomeWorkWhenBothProductAndAttributeTypeAreSet() {
}
}
In the above code sample, I would like to call doSomeWorkWhenBothProductAndAttributeTypeAreSet() when product and attribute type have been assigned. I tried calling the method after setting the second property but sometimes the product takes longer to assign so does not work as expected.
Solution
You can implement OnChanges
interface in order to check changes on input attributes, and add some logic depending on that.
export class ProductComponent implements OnInit, OnChanges {
@Input() set product(value: Product) {
_product = value;
}
_attributeType: any;
@Input() set attributeType(value: any) {
_attributeType = value;
}
ngOnChanges(simpleChange: SimpleChanges) {
if (this._attributeType && this._product) {
this.doSomeWorkWhenBothProductAndAttributeTypeAreSet();
}
// or check simpleChange to retrieve some informations :
// - new value
// - previous value
}
doSomeWorkWhenBothProductAndAttributeTypeAreSet() {
}
}
More details on official docs
Answered By - Thierry Falvo
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.