Angular 13开发动画时控制台报TS2339 isOpen属性不存在错误
报错原因
- 这是Angular模板类型检查抛出的编译错误:模板里两处用到了
isOpen属性(一处是[@openClose]动画状态绑定,一处是插值表达式显示状态文本),但SidebarComponent类里没有声明这个属性,TypeScript类型检查找不到对应属性就会抛出TS2339错误。 - 你贴出的TS代码仅包含
@Component装饰器的配置部分,组件类内部漏写了isOpen属性定义,该问题和动画本身的写法无关。
修复方法
- 在
SidebarComponent组件类中声明isOpen属性,根据业务需求设置初始值即可,参考修改后的完整组件TS代码:
import { animate, state, style, transition, trigger } from '@angular/animations'; import { Component, ElementRef, OnInit, ViewChild } from '@angular/core'; import { CommunicationService } from '../../shared-service/shared-services.service'; @Component({ selector: 'app-sidebar', templateUrl: './sidebar.component.html', styleUrls: ['./sidebar.component.scss'], animations: [ trigger('openClose', [ state('open', style({ height: '200px', opacity: 1, backgroundColor: 'yellow' })), state('closed', style({ height: '100px', opacity: 0.8, backgroundColor: 'blue' })), transition('open => closed', [ animate('1s') ]), transition('closed => open', [ animate('0.5s') ]), ]), ], }) export class SidebarComponent implements OnInit { // 补全缺失的isOpen属性,初始值可根据业务需求调整为true或false isOpen = false; constructor(private communicationService: CommunicationService) { } ngOnInit(): void { // 原有初始化业务逻辑 } // 可选:新增状态切换方法,用于手动触发动画状态切换 toggleAnimateState() { this.isOpen = !this.isOpen; } // 原有其他类属性、方法,比如@ViewChild装饰的元素、业务逻辑方法等 }
- (可选)如果需要手动触发动画切换,可以在模板中绑定事件触发切换方法,示例代码如下:
<button (click)="toggleAnimateState()">切换动画状态</button> <div [@openClose]="isOpen ? 'open' : 'closed'" class="open-close-container"> <p>The box is now {{ isOpen ? 'Open' : 'Closed' }}!</p> </div>
- 保存代码后等待项目重新编译,TS2339报错就会消失,动画可正常运行。
补充排查点:如果补全属性后动画仍无法正常工作,请确认已经在根模块
AppModule的imports数组中导入了BrowserAnimationsModule,这是Angular动画运行的必要依赖。
内容的提问来源于stack exchange,提问作者Tehseen Ullah
相关产品推荐
相关产品推荐

