【问题标题】:error in two way communication in angular 2角度2中的双向通信错误
【发布时间】:2018-01-29 14:51:10
【问题描述】:

我收到如下错误:

[ts] 预期声明或声明

当我将元素从child 传递到parent 时,即是在练习双向沟通。我没有得到什么是错误

//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++;
  }
}

【问题讨论】:

  • 任何好的(trans/)编译器都会给你错误所在的行。此外,任何好的 IDE 都会用红色强调它。你在写什么,纸?
  • 那么您是否设法修复了您的代码?

标签: angular angular2-components


【解决方案1】:

行:

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>

【讨论】:

  • 是的,它已经解决了,非常感谢@Adrien Brunelat,我是 Angular 2 的新手
  • 那么你应该接受答案。我们都会赢得声誉。
猜你喜欢
  • 2016-03-22
  • 2019-02-15
  • 2023-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-04
  • 2016-05-26
  • 2016-08-19
相关资源
最近更新 更多