我收到如下错误:
[ts] 预期的声明或声明
当我将元素从child
传递到parent
时,那是在练习 2 路通信时。我不明白错误是什么
//child
import { Component, Input, EventEmitter, Output } from '@angular/core';
//import { Hero } from './app.hero';
@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 {
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>();
this.change.emit(11);
}
//parent
import { Component, Input } from '@angular/core';
import { ChildComponent } from './app.childcomponent';
//import { Hero } from './app.Hero';
@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++;
}
}
行:
this.change.emit(11);
应该在类似于组件构造函数的方法中:
export MyComponent {
/* ... */
constructor() {
this.change.emit(11);
}
}
您也可以将其放置在 ngInit 方法中,如下所示(将extends
添加到组件中(:
export MyComponent extends OnInit {
/* ... */
ngOnInit() {
this.change.emit(11);
}
}
您的第二个模板中似乎也有拼写错误。确保bro-root
和[no]
之间有一个空格:
<bro-root [no]="count" (change)="updateFromChild($event)"></bro-root>