我有一个带有路由器 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/