2017-09-16 61 views
1

我试图做一些类似谷歌地图的角度。所以我有一个背景图像/地图,我想创建对象/组件来代替用户用鼠标点击的地图。创建组件代替点击事件

现在我正在获取x/y值。但我不确定点击事件后应该做什么。

getCoordinates(event): Coordinates { 
    let offsetLeft = document.getElementById("drawing").offsetWidth; 
    let offsetTop = document.getElementById("drawing").offsetHeight; 
    let x = event.pageX - (document.getElementById("drawing").offsetLeft); 
    let y = event.pageY - (document.getElementById("drawing").offsetTop); 
    console.log("zoom " + this.zoom); 
    console.log("x " + x/this.zoom); 
    console.log("y " + y/this.zoom); 
    console.log("element " + offsetLeft); 
    console.log("element " + offsetTop); 
    return new Coordinates(x,y); 
    } 

理想情况下,我想在用户单击表单填充时生成一个小的弹出窗口。

回答

2

传递坐标信息,以创建组件

<my-component *ngFor="let cmp of components" [info]="cmp"></my-component> 

export class ParentComponent { 
    components:Coordinates[] = []; 

    getCoordinates(event): Coordinates { 
    let offsetLeft = document.getElementById("drawing").offsetWidth; 
    let offsetTop = document.getElementById("drawing").offsetHeight; 
    let x = event.pageX - (document.getElementById("drawing").offsetLeft); 
    let y = event.pageY - (document.getElementById("drawing").offsetTop); 

    this.components.push(new Coordinates(x,y)); 
    } 
} 

使组件位置本身

export class MyComponent { 
    @Input() info:Coordinates; 

    @HostBinding('style.left.px') 
    get left() { return this.info.left; } 

    @HostBinding('style.top.px') 
    get top() { return this.info.top; } 
} 

Plunker Example

如果要添加不同类型的组件,你可以使用来自Angular 2 dynamic tabs with user-click chosen components

的想法延伸以上方法
+0

在Angular2中使用类似getElementById的JavaScript是否是一种好的做法? – RGS

+1

不确定你的意思。一般来说还是以某种方式与这个问题有关? Typescript和Angular绑定被转换成JS,你无法避免JS。你的意思是JS而不是TypeScript或使用JS库像jQuery? –

+0

是的。我的意思是,而不是在Angular2中使用JavaScript,我们可以使用TypeScript和Angular2,像ElementRef,ViewChild。我的同事告诉说,尽量避免在Angular2中使用普通的JavaScript,比如querySelectorAll。你在回答中使用了document.getElementById,这就是为什么我提出了疑问。 – RGS