peterc
peterc

Reputation: 7873

Ionic / Angular - how to initialize component without visible control initializations showing

I have an Ionic 4 / Angular 8 application, where I display a component inside a modal.

eg

const modal = await this.modalController.create({
  component: MyComponent,

 ...
  await modal.present();
 ...
 

This component contains a Form (reactive form), and has various controls initialized, and also parts hidden/shown using *ngIfs. I sent everything in the reactive form in the ngOnInit()

I have a number of @Input() passed to the component.

My problem is, when the modal opens, you can first see it uninitialized, and then it jumps around as controls are set, and bits of UI are shown / hidden via the *ngIfs.

Is there a way to have everything "hidden" until all this initialization is finished, so the user does not see all this jumping around, and controls being set?

Upvotes: 0

Views: 1091

Answers (1)

Kurt Hamilton
Kurt Hamilton

Reputation: 13515

You have at least two options here.

  1. Wrap everything in an [hidden]="!ready", where ready is a property that is set to true once everything has loaded. Using [hidden] will still let your child components load, unlike *ngIf.
<div [hidden]="!ready">
  <app-child>... secretly loading content ...</app-child>
</div>

The tiny issue with this is that you have to use [hidden] on a real DOM element - so not <ng-container>, for example.

  1. Use OnPush change detection.
@Component({
  // ... other options omitted for brevity

  changeDetection: ChangeDetectionStrategy.OnPush
})
export class MyComponent {
  constructor(private changeDetector: ChangeDetectorRef) {}

  ngOnInit(): void {
    // load all the things
    // ...

    // now trigger change detection
    this.changeDetection.detectChanges();
  }
}

It's probably a good idea to combine the two, but you could get away with either one

Both of these require that the component you are working in is aware of when all the content has loaded. If the control can't determine this at the moment, you will need to change that regardless of the approach you take.

Upvotes: 3

Related Questions