在路由器插座内将数据从子级传递到父级

bra*_*ice 8 angular

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

<router-outlet (tapVocab)="openVocabModal($event)"></router-outlet>
Run Code Online (Sandbox Code Playgroud)

似乎对我不起作用。在我的孩子中,我有:

@Output() tapVocab = new EventEmitter<string>();

callParent(val) {
    console.log('calling parent', val);
    this.tapVocab.next(val);
  }
Run Code Online (Sandbox Code Playgroud)

Md.*_*fee 12

角度

<router-outlet> 充当 Angular 根据当前路由器状态动态填充的占位符。

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

但它有两个事件:

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

停用 — 在组件被销毁时发出。

<router-outlet (activate)="componentAdded($event)" (deactivate)="componentRemoved($event)"></router-outlet>
Run Code Online (Sandbox Code Playgroud)

但我认为它对你的情况没有用。

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

common.service.ts:

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

  changeData(data: string) {
    this.data.next(data)
  }
}
Run Code Online (Sandbox Code Playgroud)

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
  }

}
Run Code Online (Sandbox Code Playgroud)

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
  }
}
Run Code Online (Sandbox Code Playgroud)