javascript - הפעל פונקציה בעת שינוי שדה
אני רוצה להפעיל פונקציה אם משתנה דגל משתנה. קראתי על ngOnChanges שפועל רק עם @Input בעוד שיש לי משתנה.
isFormCompleted: boolean = false;
ngOnInit() {
this.checkComplete();
}
checkComplete() {
/**
* Checks if all conditions are valid and then turns the flag variable to true
**/
this.isFormCompleted = true;
}
עכשיו אני רוצה להפעיל פונקציה ברגע שמשתנה הדגל משתנה ל-true. איך אני משיג את זה?
תשובה #1
אתה יכול להשתמש ב-rxjs לזה, על ידי יצירת Subject שהוא זרם שאתה יכול להירשם אליו כאשר הוא משתנה. Angular אמור לכלול את החבילות כברירת מחדל
isFormCompleted$: Subject = new Subject<boolean>(false);
ngOnInit() {
this.isFormCompleted$.subscribe({
// Here you can add your callback and do with the changing value whatever you want
next: (v) => console.log(`value: ${v}`)
});
}
checkComplete() {
this.isFormCompleted$.next(true);
}
זה תמיד יבוצע כאשר הנושא משנה את ערכו. אתה יכול להפעיל זאת על ידי קריאה ל:
this.isFormCompleted$.next(true);
תיעוד: https://rxjs.dev/guide/subject
תשובה #2
שימוש ב-getters וב-setters:
private _isFormCompleted: boolean = false;
get isFormCompleted(): boolean {
return this._isFormCompleted;
}
set isFormCompleted(value: boolean) {
this._isFormCompleted = value;
if (this._isFormCompleted) {
this.functionCall();
}
}
