【问题标题】:Passing data between components with input and output通过输入和输出在组件之间传递数据
【发布时间】:2016-12-09 19:34:22
【问题描述】:

所以我是角度二的新手,我查看了几个教程试图弄清楚如何做到这一点,但我无法让它工作。你能告诉我我在这里做错了什么吗?

所以我试图将一个布尔值从一个组件传递到另一个组件,这将触发带有 ng-class 的动画。该事件发生在子组件中。我需要家长回应。

子组件:

export class DefaultRouteViewComponent implements OnInit {
  @Input() compare: boolean = false;
  @Output() compareEvent = new EventEmitter();

  constructor(public _menu: MenuService) {}

  toggleCompare () {
    this.compare = !this.compare;
    this.compareEvent.emit({
       value: this.compare
    })
  }

父组件:

@Component({
  moduleId: module.id,
  selector: 'app-root',
  template: '<div class="app-wrapper" [ngClass]="{'hide-app' : hideApp}" (hideApp)="hideAppChange($event);" (compareEvent)="hideAppChange($event)"></div>',
  directives: NgClass, DefaultRouteViewComponent],
})
export class AppComponent implements OnInit {
  hideApp: Boolean;

  constructor() {}

  hideAppChange(event) {
     console.log(event);
  }
}

我觉得问题出在父组件模板中。不过我不确定。请帮忙!谢谢。

【问题讨论】:

  • 你的子组件的选择器是什么以及它在父模板中的使用?
  • selector: 'app-default-route-view', 是选择器。父级是标题。孩子只是路线的模板。
  • 不确定Output 在这种情况下是否有效...

标签: angular


【解决方案1】:

可能重复Passing @Input and subscribing to @Output while navigating to a Route in Angular 2 Component

如果您需要在父子路由组件之间进行通信,您可以使用Bi Directional service

你可能会看到类似的implementation here

【讨论】:

    【解决方案2】:

    'compareEvent' 事件绑定需要作为属性放置在父组件的 html 中子组件的选择器上。

    所以在父组件模板 html 中你需要这样的东西:

    <app-default-route-view (compareEvent)="hideAppChange($event)">
    </app-default-route-view>
    

    希望有帮助!

    【讨论】:

      猜你喜欢
      • 2017-10-28
      • 1970-01-01
      • 2019-06-04
      • 1970-01-01
      • 2013-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多