I am writing a directive which has 2 @Input()
variables and takes value from who ever using that directive like components.
Everything is fine. The only problem is that when there is a Observable.subscribe
in the constructor, then @Input
values are available in constructor and without Observable.subscribe
the @Input()
variable values are undefined
I know the better way to get @Input()
variable of a directive is to access them inside a life cycle hook like ngOnInit
or ngOnChange
but my question is: why is this available in some cases and not available in other cases in a directive.
<div authorizedme
[permission]="'manager'"
[auth]="department"
class="col-2 data-object-link">your salary is $90,000,0000
directive
If inside the directive's constructor below the subscribe
code is there, then permission and auth is available, and if it's commented out then both of the @Input()
variables are undefined
.
this.userService.getUser().subscribe((user) => {
this.user = user;
if (this.authorized()) {
this.elementRef.nativeElement.style.display = 'block';
}
});
Below is the entire directive code
@Directive({
selector: '[authorizedme]'
})
export class AuthorizedDirective implements OnInit {
@Input() permission: string;
@Input() auth: string;
private user: any;
constructor(private elementRef: ElementRef, private currentUserService: userService) {
this.elementRef.nativeElement.style.display = 'none';
this.currentUser = this.userService.userAuthorizations;
/*this.currentUserService.getUser().subscribe((user) => {
this.user = user;
if (this.authorized()) {
this.elementRef.nativeElement.style.display = 'block';
}
});*/
}
public authorized() {
return this.user || authorize;
}
}