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.
CodePudding user response:
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
CodePudding user response:
Angular has some lyfecycle hooks that can be used to execute parts of logic only in determinate moments, this is a list of every lifecycle hook a component has:
ngOnChanges()
ngOnInit()
ngDoCheck()
ngAfterContentInit()
ngAfterContentChecked()
ngAfterViewInit()
ngAfterViewChecked()
ngOnDestroy()
Now, angular calls ngOnChanges
the first time before the ngOnInit
to let you access the @Input()
variables with their values on init. Said that you have two main ways of achieving your goal:
- By using
ngOnChanges()
:
public ngOnChanges(changes: SimpleChanges): void {
// you can check here if your props are set and if so call your method
console.log(changes['YOUR_PROP'].currentValue);
}
Note that this method will be called on every @Input() prop update
- By directly using
ngOnInit()
:
public ngOnInit(): void {
// here you can access your props since angular has called onChanges before and has already initialized them
}