angular - 在路由器 socket 内将数据从子级传递给父级

标签 angular

我有一个带有路由器 socket 的父组件。我想用子事件调用父函数。我了解@Input() 和@Output,但是如何将它们与路由器 socket 一起使用

<router-outlet (tapVocab)="openVocabModal($event)"></router-outlet>

似乎对我不起作用。在我的 child 中,我有:
@Output() tapVocab = new EventEmitter<string>();

callParent(val) {
    console.log('calling parent', val);
    this.tapVocab.next(val);
  }

最佳答案

来自 angular

<router-outlet> Acts as a placeholder that Angular dynamically fills based on the current router state.


<router-outlet>不提供将数据绑定(bind)到加载的组件或将事件从它们发送到父组件的方法。

但它有两个事件:

activate — 在实例化新组件时发出。

deactivate — 当组件被销毁时发出。
<router-outlet (activate)="componentAdded($event)" (deactivate)="componentRemoved($event)"></router-outlet>

但我认为这对您的情况没有用。

但是您可以像使用服务在两个不相关的组件之间进行任何其他通信一样进行通信。

common.service.ts:
@Injectable()
export class CommonService {
  private data = new BehaviorSubject('default data');
  data$ = this.data.asObservable();

  changeData(data: string) {
    this.data.next(data)
  }
}

app.component.ts:
@Component({
  selector: 'app-component',
  template: `<p>{{data}}</p>`
})
export class AppComponent implements OnInit {

  data: string;

  constructor(private service: CommonService) { }

  ngOnInit() {
    this.service.data$.subscribe(res => this.data = res)  //read the invoked data or default data
  }

}

child.component.ts:
@Component({
  selector: 'app-component-two',
  template: `
    <p>{{data}}</p>
    <button (click)="newData()">Next Data</button>`
})
export class ComponentTwoComponent implements OnInit {

  data: string;

  constructor(private service: CommonService) { }

  ngOnInit() {
    this.service.data$.subscribe(res => this.data = res)
  }
  newData() {
    this.service.changeData('Changed Data');  //invoke new Data
  }
}

关于angular - 在路由器 socket 内将数据从子级传递给父级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57878617/

相关文章:

javascript - "@angular/http"和 "@angular/common/http"中的 Angular 的 httpClient 有什么区别?

html - NgFor 没有显示我给他的数组

angular - @ngrx 具有多个有效负载的操作

javascript - 无法使用 Angular 6将图像下载为zip文件

javascript - 如何在 Angular4 中实现 ngFor 回调?

angular - Ionic 2/Typescript 构建失败 : Unexpected character '@'

javascript - ionic 混合移动应用程序获取设备位置

javascript - 如何在 Angular 中测试 JSONP HTTP 请求?

从 typescript 调用 Javascript 原型(prototype)函数

html - 切换背景图片 - Angular 2