当我们在一个 Angular 组件的模板中使用 ng-content,并且想在其中添加动画时,有时会发现 ng-content 不起作用,导致动画无法正常展现。这是因为 ng-content 对动画造成了影响。
解决这个问题的方法是在 ng-content上添加一个 @ContentChildren 装饰器,以便在动画中使用它。示例如下:
import { Component, ContentChildren, QueryList } from '@angular/core';
import { trigger, transition, animate, style } from '@angular/animations';
@Component({
selector: 'app-my-component',
template: `
`,
animations: [
trigger('myAnimation', [
transition(':enter', [
style({ opacity: 0 }),
animate('1s', style({ opacity: 1 }))
]),
transition(':leave', [
animate('1s', style({ opacity: 0 }))
])
])
]
})
export class MyComponent {
@ContentChildren('') myContent: QueryList;
}
在上面的代码中,我们给 ng-content 添加了一个空的 @ContentChildren 装饰器,并在组件的模板上添加了动画。此时,我们就可以愉快的在组件中同时使用 ng-content 和动画了。