如何在模板基于ngTemplate的Angular组件中添加动画

时间:2018-08-28 16:40:48

标签: angular angular6 angular-animations

该组件的模板就是这样

<ng-template #primary @fading><ng-content select="[primary]"></ng-content></ng-template> // gives error
<ng-template #secondary> <ng-content select="[secondary]"></ng-content></ng-template>


<ng-container *ngIf="(mode | async)=== mode_layout_100_0">
  <div class="h-100">
    <ng-container *ngTemplateOutlet="primary"></ng-container>
  </div>
</ng-container>
<ng-container *ngIf="(mode | async)=== mode_layout_0_100">
  <div class="h-100">
    <ng-container *ngTemplateOutlet="secondary"></ng-container>
  </div>
</ng-container>
<ng-container *ngIf="(mode | async)=== mode_layout_33_66">
  <div class="d-flex flex-row h-100 split-view" @fading> // dosent work 
    <div class="d-none d-sm-none d-md-none d-lg-block col-lg-4 p-0">
      <ng-container *ngTemplateOutlet="primary"></ng-container>
    </div>
    <div class="col-12 col-sm-12 col-md-12 col-lg-8 p-0 view-seperator">
      <ng-container *ngTemplateOutlet="secondary"></ng-container>
    </div>
  </div>
</ng-container>
<ng-container *ngIf="(mode | async)=== mode_layout_66_33">
  <div class="d-flex flex-row h-100 split-view">
    <div class="col-sm-8 p-0">
      <ng-container *ngTemplateOutlet="primary"></ng-container>
    </div>
    <div class="col-sm-4 p-0 view-seperator">
      <ng-container *ngTemplateOutlet="secondary"></ng-container>
    </div>
  </div>
</ng-container>

它充当管理器,根据我们想要的主要或次要或两者的混合以及33%到66%的布局来分割视图。

我已将以下元数据添加到装饰器

animations: [
    trigger('fading', [
      transition(':enter', animate('800ms ease-out')),
      transition(':leave', animate('800ms ease-in')),
    ])
  ]

我要实现的是,如果嵌套使用此组件,则视图从主模式更改为次模式。会有轻松自如的流畅动画。

如何将尝试添加到ng-template的动画标签添加到错误代码中;如果我将其添加到每个div中,则该标签工作正常。

1 个答案:

答案 0 :(得分:2)

As far as I know this is not possible using ng-template at least for Angular 6 (and 7). This Angular directive is managed internally by it, so I haven't found anything by a thorough search.

What I've used to overcome this situation is adding a variable inside the component code and use in the component HTML markup with a conditional *ngIf directive evaluating this. For cases of using rxjs Observable, subscribe to it and then change the loading value to true. Just don't forget to add your animation properly to the HTML divs you want to animate.

my.component.html

<div *ngIf="loading" @animation>
...
</div>
<div *ngIf="!loading" @animation>
...
</div>

my.component.ts

@Component({
  selector: 'app-component',
  templateUrl: './my.component.html',
  styleUrls: ['./my.component.css'],
  animations: [
    ...
  ]
})
export class MyComponent implements OnInit {
  loading: boolean = true;
  ...

  ngOnInit() {
    this.config$.subscribe(() => {
      this.loading = false;
    })
  }
}