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++; } }
为什么这样改?
- 符合TypeScript类语法:将
emit调用移到ngOnInit方法后,代码就处于合法的可执行上下文里了,编译器不会再报错。ngOnInit是Angular组件初始化完成后触发的生命周期钩子,很适合用来执行这类初始化时的事件发射操作。 - 修复模板语法:给
[no]绑定前加上空格,确保模板解析器能正确识别属性绑定语法。
这样修改后,你的子组件就能正常向父组件传递值,错误也会消失啦!
内容的提问来源于stack exchange,提问作者keshava shourie.b
相关产品推荐
相关产品推荐

