点击链接时,我试图在列表中切换子菜单。
https://plnkr.co/edit/ZoOGJD8FUbBfPgHTKlPh?p=preview
模板
<ul>
<li><a><i class="zmdi zmdi-home"></i> Home</a></li>
<li>
<a (click)="toggleNavigationSub($event)">Profile</a>
<ul [@toggleHeight]="navigationSubState">
<li><a>Settings</a></li>
<li><a>Privacy</a></li>
</ul>
</li>
<li>
<a (click)="toggleNavigationSub($event)">Messages</a>
<ul [@toggleHeight]="navigationSubState">
<li><a>Notifications</a></li>
<li><a>Private</a></li>
</ul>
</li>
</ul>
如您所见,我在最后2 li
个标签内有2个子菜单。我能够使用Angular2动画创建slideToggle动画,但我无法正确实现它。
动画
animations: [
trigger('toggleHeight', [
state('inactive', style({
height: '0',
opacity: '0'
})),
state('active', style({
height: '*',
opacity: '1'
})),
transition('inactive => active', animate('200ms ease-in')),
transition('active => inactive', animate('200ms ease-out'))
])
]
功能
navigationSubState: string = 'inactive';
toggleNavigationSub(event) {
event.preventDefault();
this.navigationSubState = (this.navigationSubState === 'inactive' ? 'active' : 'inactive');
}
当我通过点击a
标签切换动画时,所有子菜单都会同时切换。如何限制仅受到单击的子菜单的切换?
答案 0 :(得分:3)
因为两个菜单的动画都被连接到控制状态的一个变量navigationSubState
,所以它们都受到每个切换操作的影响。
相反,将单个字符串属性更改为从菜单名称到字符串的映射,并仅切换该菜单项。
以下是forked Plunkr,相关代码如下:
@Component({
selector: 'my-app',
template: `
<ul>
<li><a><i class="zmdi zmdi-home"></i> Home</a></li>
<li>
<a (click)="toggleNavigationSub('Profile', $event)">Profile</a>
<ul [@toggleHeight]="navigationSubState.Profile">
<li><a>Settings</a></li>
<li><a>Privacy</a></li>
</ul>
</li>
<li>
<a (click)="toggleNavigationSub('Messages', $event)">Messages</a>
<ul [@toggleHeight]="navigationSubState.Messages">
<li><a>Notifications</a></li>
<li><a>Private</a></li>
</ul>
</li>
</ul>
`,
animations: [
trigger('toggleHeight', [
state('inactive', style({
height: '0',
opacity: '0'
})),
state('active', style({
height: '*',
opacity: '1'
})),
transition('inactive => active', animate('200ms ease-in')),
transition('active => inactive', animate('200ms ease-out'))
])
]
})
export class App {
navigationSubState: { [menu: string]: string} = {
Profile: 'inactive',
Messages: 'inactive'
};
toggleNavigationSub(menuName: string, event: Event) {
event.preventDefault();
this.navigationSubState[menuName] = (this.navigationSubState[menuName] === 'inactive' ? 'active' : 'inactive');
}
constructor() {
}
}