为主机元素添加Angular动画

33
我为主机添加了动画。
@Component({
   ....,
   animations: [
      trigger('slideIn', [
          ...
      ])
   ],
   host: {
      '[@animation]': 'condition'
   }
}

之前代码运行良好,但编译时提示该方法已过时,建议使用@HostBinding ...

@HostBinding('[@animation]') get slideIn() {
   return condition;
}

这导致我出现了一个错误

Can't bind to '[@animation' since it isn't a known property of 'my-component-selector'.

但是我无法将动画添加到我的模块中,我该怎么办?
2个回答

50

使用@HostBinding()时方括号不是必需的。

@HostBinding('@slideIn') get slideIn() {

有两个装饰器@HostBinding()@HostListener(),因此在使用()[]时不需要区分,但在使用host: [...]时需要区分。


16

我写这篇答案是因为我在语法上遇到了一些困难,而我喜欢用“白痴式”的例子,但Günter的答案是正确的。

我所需要做的是:

    @Component({
        selector: 'app-sidenav',
        templateUrl: './sidenav.component.html',
        styleUrls: ['./sidenav.component.scss'],
        animations: [
            trigger('toggleDrawer', [
                state('closed', style({
                    transform: 'translateX(0)',
                    'box-shadow': '0px 3px 6px 1px rgba(0, 0, 0, 0.6)'
                })),
                state('opened', style({
                    transform: 'translateX(80vw)'
                })),
                transition('closed <=> opened', animate(300))
            ])
        ]
    })
    export class SidenavComponent implements OnInit {

        private state: 'opened' | 'closed' = 'closed';

        // binds the animation to the host component
        @HostBinding('@toggleDrawer') get getToggleDrawer(): string {
            return this.state === 'closed' ? 'opened' : 'closed';
        }

        constructor() { }

        ngOnInit(): void {
        }

        // toggle drawer
        toggle(): void {
            this.state = this.state === 'closed' ? 'opened' : 'closed';
        }

        // opens drawer
        open(): void {
            this.state = 'opened';
        }

        // closes drawer
        close(): void {
            this.state = 'closed';
        }

    }

1
有人知道如何将 (@toggleDrawer.done)(动画结束时的回调)绑定到主机吗? - Frank N
3
@FrankNocke 你试过使用 @HostListener('@toggleDrawer.done', ['$event']) 吗? 可能有效。 - tinnick
1
@tinnick 哇,它真的像这样工作了!@HostListener('@transformPanel.done', ['$event']) 谢谢! - Maxime Lyakhov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接