You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 13开发动画时控制台报TS2339 isOpen属性不存在错误

报错原因
  • 这是Angular模板类型检查抛出的编译错误:模板里两处用到了isOpen属性(一处是[@openClose]动画状态绑定,一处是插值表达式显示状态文本),但SidebarComponent类里没有声明这个属性,TypeScript类型检查找不到对应属性就会抛出TS2339错误。
  • 你贴出的TS代码仅包含@Component装饰器的配置部分,组件类内部漏写了isOpen属性定义,该问题和动画本身的写法无关。
修复方法
  1. 在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装饰的元素、业务逻辑方法等
}
  1. (可选)如果需要手动触发动画切换,可以在模板中绑定事件触发切换方法,示例代码如下:
<button (click)="toggleAnimateState()">切换动画状态</button>
<div [@openClose]="isOpen ? 'open' : 'closed'" class="open-close-container">
  <p>The box is now {{ isOpen ? 'Open' : 'Closed' }}!</p>
</div>
  1. 保存代码后等待项目重新编译,TS2339报错就会消失,动画可正常运行。

补充排查点:如果补全属性后动画仍无法正常工作,请确认已经在根模块AppModule的imports数组中导入了BrowserAnimationsModule,这是Angular动画运行的必要依赖。

内容的提问来源于stack exchange,提问作者Tehseen Ullah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.02 04:45:38