how to show/hide mdbCollapse from component.ts ?


Topic: how to show/hide mdbCollapse from component.ts ?

herve pro asked 6 years ago

I have a mdbCollapse component and I can show/hide it from html -> ok

My question is : how can I show/hide this mdbComponent directly from the .ts associated to the template ?

Thank you


Damian Gemza staff answered 6 years ago

Dear herve,

Just use the @ViewChild decorator to get the handle to the collapse element from the template, and use the toggle method from it.

Please take a look at the below code:

.html:

<button mdbBtn color="primary" class="waves-light" type="button" (click)="test.toggle()" mdbWavesEffect>
        Toggle collapse
      </button>

      <div class="" mdbCollapse #test="bs-collapse">
        <p>Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. Nihil anim
          keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident.</p>
      </div>

.ts:

@ViewChild('test') collapse: CollapseComponent;

  ngAfterViewInit() {
    setTimeout(() => {
      this.collapse.toggle();
    }, 0);
  }

Best Regards,

Damian


herve pro answered 6 years ago

It works ! Thank you very much Just one thing : Why do you encapsulate "this.collapse.toggle()" in a setTimeout with 0 ms ?

Thanks


Damian Gemza staff answered 6 years ago

Because there's changing animation state quickly, and without this setTimeout you would get error ExpressionChangedAfterItHasBeenCheckedError.

This error would be visible only in ngAfterViewInit.

If you want to open / hide after some actions, you don't have to use setTimeout.

If you don't want to use setTimeout, you could try to use cdRef.detectChanges() after calling the toggle method.

Best Regards,

Damian


Please insert min. 20 characters.

FREE CONSULTATION

Hire our experts to build a dedicated project. We'll analyze your business requirements, for free.

Status

Resolved

Specification of the issue
  • User: Pro
  • Premium support: No
  • Technology: MDB Angular
  • MDB Version: 7.4.0
  • Device: pc
  • Browser: chrome
  • OS: w7
  • Provided sample code: No
  • Provided link: No