'Angular loads children components before *ngIf condition runs and then hides them
I have one component that is being used for authorization. If a user is not authorized they won't be able to see specific elements. I have some HTTP calls to the particular elements. Like get projects.
Let me give you an example here:
app.component.ts
<authorized>
<app-project></app-project>
</authorized>
The authorize component is suppose to protect app-project to be loaded because I have *ngIf in the authorize.component.ts.
authorize.component.ts:
<ng-template #authorized *ngIf="isAuthorized">
<ng-content></ng-content> <<--- app-project
</ng-template>
Is there a way to prevent the app-project to be loaded before isAuthorized condition is executed?
@Component({
selector: 'app-project',
template: `
<div>I'm not visible</div>`
})
export class ProjectComponent {
constructor() {
alert(`This message shouldn't be called`);
}
}
@Component({
selector: 'app-authorize',
template: `
<div *ngIf="false">
<ng-content></ng-content>
</div>
`
})
export class AuthorizeComponent {
constructor() {
}
}
@Component({
selector: 'app-root',
styleUrls: ['./app.component.css'],
template: `
<app-authorize>
<app-project></app-project>
</app-authorize>
`
})
export class AppComponent {
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
