RasMason
RasMason

Reputation: 2212

Apply animation to dynamically loaded component Angular 5

Hi trying to apply an animation to a component that I'm loading in via the ComponentFactory

I'v tried applying an angular animation to it's inner selector and triggering onInit

<p  [@detailExpand]="expand">
  {{ content1 }} {{ content2 }}
</p>

in component to be loaded ts file:

@Component({
  selector: 'app-rowdetail',
  templateUrl: './rowdetail.component.html',
  styleUrls: ['./rowdetail.component.scss'],
  animations: [
    trigger('detailExpand', [
      state('false', style({ 'height': '0px', 'minHeight': '0', 'visibility': 'hidden' })),
      state('true', style({ 'height': '*', 'visibility': 'visible' })),
      transition('expanded <=> collapsed', animate('1000ms')),
    ]),
  ]
})
export class RowdetailComponent implements OnInit, OnDestroy {
  @Input() content1: string;
  @Input() content2: string;
  @Input('expand') expand: string;
  constructor() { }

  ngOnInit() {
    this.expand = 'false'
    setTimeout(() => {
      this.expand = 'true'
      console.log(this.expand)
    }, 500)

  }
  ngOnDestroy() {
    this.expand = 'false'
    console.log(this.expand)
  }
}

The function that loads the component:

 expandRow(index: number, row) {
    console.log(this.expandedRow, index)
    if (this.expandedRow != null) {
      // clear old message
      this.containers.toArray()[this.expandedRow].clear();
    }

    if (this.expandedRow === index) {
      this.expandedRow = null;
      return;
    } else {
      this.expandedRow = index
      this.expand = 'expanded'
      const container = this.containers.toArray()[index];
      const factory: ComponentFactory<RowdetailComponent> = this.resolver.resolveComponentFactory(RowdetailComponent);
      const messageComponent = container.createComponent(factory);

      messageComponent.instance.content1 = "some text";
      messageComponent.instance.content2 = "some more text";
    // setTimeout(() => {  //this.renderer.addClass(messageComponent.hostView.rootNodes[0].querySelector('p'), 'element-animation')
          // }, 1000)


    }
  }

I've also tried applying a class with a css animation, but nothing has worked, no animation plays at all Does anyone have an idea what best practice is?

Upvotes: 0

Views: 2467

Answers (1)

user4676340
user4676340

Reputation:

Your transition might be the issue :

transition('expanded <=> collapsed', animate('1000ms'))

Your states are called 'false' and 'true'. You have to define a transition on the states, not on whatever you are trying to do.

trigger('detailExpand', [
  state('false', style({ 'height': '0px', 'minHeight': '0', 'visibility': 'hidden' })),
  state('true', style({ 'height': '*', 'visibility': 'visible' })),
  transition('true <=> false', animate('1000ms')),
]),

(Although I'm not sure this will work because of the words that you used. If it doesn't, try using 'A' and 'B' in place of true and false).

Upvotes: 3

Related Questions