Home > Software design >  Angular: Is there a way to stop a component from initializing it's view?
Angular: Is there a way to stop a component from initializing it's view?

Time:03-11

What I am trying to do is, if this.pageService.getForbidden() return true.

I don't want this component to load or initialized, is there a way to achieve this?

export class ViewRComponent extends ViewRulesParentComponent implements OnInit, AfterViewInit {

    constructor( protected readonly pageService: PageService,
               ) {
        if( this.pageService.getForbidden()){
        // this.pageService.getForbidden() is true, I don't want this component to load 
            return;
        }
    }
}

CodePudding user response:

If you got a parent component you can just use a <div> with *ngIf=pageService.getForbidden()

something like this:

parent.html

<div *ngIf=pageService.getForbidden()>
  <view-r-component></view-r-component>
</div>

where <view-r-component> its your ViewRComponent component

i hope it works for you!

CodePudding user response:

I don't know how your application is structured, but you can use Angular Guards to prevent the component to be loaded, something like CanActivate and CanLoad guards can help you.

https://angular.io/api/router/CanActivate

https://angular.io/api/router/CanLoad

  • Related