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

Angular 2双向通信出现[ts] Declaration or statement expected错误求助

解决Angular 2子组件双向通信中的Declaration or statement expected错误

嘿,我一眼就揪出问题所在啦!你碰到的这个TypeScript错误,根源是子组件里的代码写法不符合类的语法规则,咱们一步步来修正:

错误原因分析

在你的ChildComponent类里,你直接把this.change.emit(11);写在了类的顶层作用域中——这可是TypeScript的大忌!TypeScript类的结构里,只能在方法、构造函数或者生命周期钩子里写可执行语句,直接在类顶层放执行代码会被编译器判定为无效的声明/语句,所以才会抛出Declaration or statement expected错误。

另外还要提个小细节:父组件模板里的<bro-root[no]="count"少了个空格,应该写成<bro-root [no]="count",不然可能会触发模板解析错误。

修正后的代码

子组件(修正版)

import { Component, Input, EventEmitter, Output, OnInit } from '@angular/core';

@Component({
  selector: 'bro-root',
  template:`
    <div>
      <h1>name:</h1>
      <h2>{{fname}}</h2>
      <h2>{{sname}}</h2>
      <h2 style="background-color:red;width:80px;">{{bruz}}</h2>
      <h2 style="background-color:red;width:80px;">{{no}}</h2>
    </div>
  `,
})
export class ChildComponent implements OnInit {
  fname:string = "tom";
  sname:string = "jerry";
  gender:string = "male";
  age:number = 20;

  @Input() bruz:string;
  @Input() no:number;
  @Output() change:EventEmitter<number> = new EventEmitter<number>();

  // 把emit调用放到ngOnInit生命周期钩子中,组件初始化时执行
  ngOnInit() {
    this.change.emit(11);
  }
}

父组件(修正版)

import { Component } from '@angular/core';
import { ChildComponent } from './app.childcomponent';

@Component({
  selector: 'app-root',
  template: `
    <bro-root [no]="count" (change)="updateFromChild($event)"></bro-root>
  `,
})
export class AppComponent {
  title = 'app works!';
  count:number = 10;

  updateFromChild($event) {
    this.count++;
  }
}

为什么这样改?

  1. 符合TypeScript类语法:将emit调用移到ngOnInit方法后,代码就处于合法的可执行上下文里了,编译器不会再报错。ngOnInit是Angular组件初始化完成后触发的生命周期钩子,很适合用来执行这类初始化时的事件发射操作。
  2. 修复模板语法:给[no]绑定前加上空格,确保模板解析器能正确识别属性绑定语法。

这样修改后,你的子组件就能正常向父组件传递值,错误也会消失啦!

内容的提问来源于stack exchange,提问作者keshava shourie.b

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:52:08