您好我正在尝试使用angulars动画API动画主机元素的高度。这是我的代码:
import { animate, state, style, transition, trigger} from '@angular/core';
export class SlideToggleOption {
public static AnimationName: string = 'slideToggle';
public static Visible: string = 'visible';
public static Hidden: string = 'hidden';
}
export function SlideToggleAnimation() {
return trigger(SlideToggleOption.AnimationName, [
state(SlideToggleOption.Visible, style({ height: 'auto', overflow: 'hidden' })),
state(SlideToggleOption.Hidden, style({ height: 0, overflow: 'hidden' })),
transition(`${SlideToggleOption.Visible} => ${SlideToggleOption.Hidden}`, animate('5000ms ease-in')),
transition(`${SlideToggleOption.Hidden } => ${SlideToggleOption.Visible}`, animate('5000ms ease-out'))
]);
}
import { Component, Input, OnInit, OnChanges, ElementRef, HostBinding } from '@angular/core';
import { SlideToggleAnimation, SlideToggleOption } from './../../animations/slide-toggle.animation';
@Component({
selector: 'dropdown-menu',
moduleId: module.id,
styleUrls: ['dropdown-menu.style.css'],
templateUrl: 'dropdown-menu.view.html',
animations: [SlideToggleAnimation()]
})
export class DropdownMenuComponent implements OnInit, OnChanges {
@Input() menuItems;
@Input() position;
@Input() isDropdownMenuVisible: boolean;
@HostBinding('class') hostItemPositionClass;
@HostBinding('@slideToggle') dropdownAnimationState = SlideToggleOption.Hidden;
element: HTMLElement;
constructor(private elementRef: ElementRef) {
this.element = elementRef.nativeElement;
}
ngOnInit() {
this.element.parentElement.style.position = 'relative';
this.hostItemPositionClass = `menu-container-${this.position}`;
this.dropdownAnimationState = SlideToggleOption.Hidden;
}
ngOnChanges() {
this.dropdownAnimationState =
this.isDropdownMenuVisible ? SlideToggleOption.Visible : SlideToggleOption.Hidden;
}
}
这是我的HTML:
<div class="menu-item" *ngFor="let menuItem of menuItems">
<icon iconClass="{{menuItem.icon}}"></icon>
<span>{{menuItem.text}}</span>
</div>
当我使用这个组件时,html看起来像这样:
<button class="btn-icon"
(click)="isMoreDropdownMenuVisible = !isMoreDropdownMenuVisible">
<icon iconClass="icon-more"></icon>
</button>
<dropdown-menu [menuItems]="navSectionRightItems"
[position]="dropdownMenuPosition"
[isDropdownMenuVisible]="isMoreDropdownMenuVisible">
</dropdown-menu>
在父组件中[isMoreDropdownMenuVisible]是一个默认设置为false的布尔值。
我省略了[menuItems]和[position]属性,因为它们与当前问题无关。
当我点击带有btn-icon类的按钮时,我收到以下错误:
我做错了什么?
答案 0 :(得分:2)
当角度变化检测导致变化时,Angular并不感兴趣。变更检测会调用ngOnInit()
。
要解决注入ChangeDetectorRef
constructor(private cdRef: ChangeDetectorRef) {}
并在修改属性后调用detectChanges()
以显式调用更改检测
ngOnInit() {
this.element.parentElement.style.position = 'relative';
this.hostItemPositionClass = `menu-container-${this.position}`;
this.dropdownAnimationState = SlideToggleOption.Hidden;
this.cdRef.detectChanges();
}