将角度动画添加到主机元素

Oli*_*ner 21 animation angular angular-animations

我通过动画添加了一个动画

@Component({
   ....,
   animations: [
      trigger('slideIn', [
          ...
      ])
   ],
   host: {
      '[@animation]': 'condition'
   }
}
Run Code Online (Sandbox Code Playgroud)

哪个运作良好,在编译时我被告知这已被弃用,我应该使用@HostBinding ......

@HostBinding('[@animation]') get slideIn() {
   return condition;
}
Run Code Online (Sandbox Code Playgroud)

这让我错了

Can't bind to '[@animation' since it isn't a known property of 'my-component-selector'.
Run Code Online (Sandbox Code Playgroud)

但我无法在我的模块中添加动画..我该怎么办?

Gün*_*uer 37

方括号不是必需的 @HostBinding()

@HostBinding('@slideIn') get slideIn() {
Run Code Online (Sandbox Code Playgroud)

有两个装饰器@HostBinding(),@HostListener()因此区别()[]不必要,而它是何时host: [...]使用.


Dav*_*eto 9

我写这个答案是因为我在语法上有点挣扎,我喜欢傻瓜的例子,但君特的答案是正确的。

我必须做的:

    @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';
        }

    }
Run Code Online (Sandbox Code Playgroud)

  • @FrankNocke你试过`@HostListener('@toggleDrawer.done', ['$event'])`吗?可能有用。 (3认同)