Issue
Sometimes changes are not reflected in Angular unless the code is wrapped in a "setTimeout" method. Im wondering, is there a "cleaner" or "more Angular" way to achieve the same functionality?
The situation I am referring to is when I have a ViewChild
with content being projected into it but I can't "see" what's in that view child unless I try to do so within a setTimeout method within AfterContentInit
ngAfterContentInit(): void {
setTimeout(() => {
// This logs "undefined" if not wrapped in
// a setTimeout
console.log(this.projectedContent);
})
}
Solution
You can use ChangeDetectorRef
A little example: focus a input under a *ngIf
<button (click)="focus()">focus</button>
<input #myinput *ngIf="toogle" />
@ViewChild('myinput') el: ElementRef;
constructor(private cdr: ChangeDetectorRef) {}
focus() {
if (!this.toogle) {
this.toogle = true;
this.cdr.detectChanges();
this.el.nativeElement.focus();
} else this.toogle = false;
}
Another way is using a decorator like NetBasal
function timeout(milliseconds: number = 0) {
return function (
target: any,
propertyKey: string,
descriptor: PropertyDescriptor
) {
const originalMethod = descriptor.value;
descriptor.value = function () {
setTimeout(() => {
originalMethod.apply(this, arguments);
}, milliseconds);
};
return descriptor;
};
}
//use:
focus() {
if (!this.toogle) {
this.toogle = true;
this.setFocus();
} else this.toogle = false;
}
@timeout()
setFocus() {
this.el.nativeElement.focus();
}
See stackblitz
Answered By - Eliseo
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.