在Angular 6中,可以通过以下步骤从一个组件传递id到另一个组件:
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-receiver',
template: `
Received ID: {{ receivedId }}
`
})
export class ReceiverComponent {
@Input() receivedId: number;
}
import { Component, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'app-sender',
template: `
`
})
export class SenderComponent {
@Output() idEvent = new EventEmitter();
sendId() {
const id = 123; // replace with your id
this.idEvent.emit(id);
}
}
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: `
`
})
export class ParentComponent {
receivedId: number;
receiveId(id: number) {
this.receivedId = id;
}
}
这样,当点击发送组件中的按钮时,id将通过事件传递给父组件的方法,父组件将其存储在变量中,并将其传递给接收组件,接收组件将在模板中显示id。
请注意,上述代码只是一个示例,你需要根据你的实际需求进行相应的修改。