我不太了解角度2,我知道这很简单,但是我似乎无法确定。
export class ActivityDesignerComponent {
whatever: any;
@ViewChild('canvasTest') canvasTest: ElementRef;
constructor() {}
// Mouse Sidebar Actions
openMouseNav() {
document.getElementById("mouse_sidenav").style.width = "292px";
}
closeMouseNav() {
document.getElementById("mouse_sidenav").style.width = "0";
}
mouseClickNav() {
document.getElementById('mouseClickNav').style.width = '319px';
let ctx: CanvasRenderingContext2D =
this.canvasTest.nativeElement.getContext('2d');
ctx.canvas.addEventListener('mousemove', function (event) {
var mouseX = event.clientX - ctx.canvas.offsetLeft;
var mouseY = event.clientY - ctx.canvas.offsetTop;
// var status = document.getElementById('status');
// status.innerHTML = mouseX + ' | ' + mouseY;
});
ctx.canvas.addEventListener('click', function (event) {
var mouseX = event.clientX - ctx.canvas.offsetLeft;
var mouseY = event.clientY - ctx.canvas.offsetTop;
console.log('Mouse Click At:', mouseX + ' | ' + mouseY);
this.whatever = mouseX;
});
}
}
它的控制台日志很好。
我想将mouseX变量输出到html中的段落标签。我相信这是通过[(ngModel)]实现的,但我不知道如何实现。想法?
答案 0 :(得分:0)
关注user184994的答案...
两个事件侦听器中未保留this
的值。
编辑您的函数以使用ES6 arrow syntax,this.whatever
将按预期更新。
ctx.canvas.addEventListener('click', (event) => {
var mouseX = event.clientX - ctx.canvas.offsetLeft;
var mouseY = event.clientY - ctx.canvas.offsetTop;
console.log('Mouse Click At:', mouseX + ' | ' + mouseY);
connsole.log(this); // `this` is now equal to an instance of ActivityDesignerComponent
this.whatever = mouseX;
});
或者,您可以完全避免使用匿名函数。通过将逻辑移到ActivityDesignerComponent方法中,还可以通过使用the bind method来保留this
的含义。
updateMousePos(): void {
const mouseX = event.clientX - ctx.canvas.offsetLeft;
const mouseY = event.clientY - ctx.canvas.offsetTop;
console.log('Mouse Click At:', mouseX + ' | ' + mouseY);
connsole.log(this); // `this` is still equal to an instance of ActivityDesignerComponent
this.whatever = mouseX;
}
....
ctx.canvas.addEventListener('click', this.updateMousePos.bind(this);
Working Example on StackBlitz.
值得补充的是,这种行为并不是Angular甚至TypeScript所独有的。这就是JavaScript的工作方式。