我正在研究什么是Angular中相当简单的ChartJS图。当用户单击图形中的条形时,我想将用户路由到新视图,但使用他们单击的条形的上下文。
从onClick函数内部,我不确定如何访问router
或schedule$
成员。
我先感谢您的帮助。
export class ScheduleDashboardComponent implements OnInit {
schedule$: Observable<Schedule>;
@ViewChild('canvas') canvas: ElementRef;
public ctx: CanvasRenderingContext2D;
constructor(
private route: ActivatedRoute,
private router: Router,
private service: SchedulingService,
private eventService: SchedulingEventsService
) {
}
ngOnInit() {
this.schedule$ = this.route.paramMap.pipe(
switchMap((params: ParamMap) =>
this.service.getSchedule(params.get('id')))
);
}
ngAfterViewInit() {
this.ctx = (<HTMLCanvasElement>this.canvas.nativeElement).getContext('2d');
let labels = [];
let games = [];
let gamesColour = [];
for (var i = 1; i < 27; i++) {
labels.push("Week " + i);
games.push(Math.round(Math.random() * 50));
gamesColour.push("#1ab394");
}
new Chart(this.ctx, {
type: 'bar',
data: {
labels: labels,
fillOpacity: .8,
datasets: [{
label: "Games",
backgroundColor: gamesColour,
data: games
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
onClick: function(e) {
console.log('Bar Click');
var element = this.getElementAtEvent(e);
if (element.length) {
// Get Bar Context
console.log(element[0]);
}
// Navigate to route
// This fails as the function doesn't know what 'this' is
this.router.navigate(['/admin/scheduling/calendar', this.schedule$.id]);
}
}
});
}
}