Angular-在复选框上添加事件

Adr*_*ien 0 javascript jquery openlayers angular

我正在用Angular用OpenLayers编程一个地图应用程序,我想在复选框上添加一些事件。我创建了带有两个菜单复选框的mat-button。

所有地图组件都在app.component.ts文件中,而带有复选框的菜单创建了一个app.component.html文件。

app.component.html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
  </head>

    <body>

      <div class="header">
          <mat-toolbar>OpenLayers</mat-toolbar>

          <div class="menu">
              <button mat-button [matMenuTriggerFor]="menu">Marqueurs</button>
              <mat-menu #menu="matMenu">
                <input type="checkbox" id="piscine" name="piscine" value="piscine">
                <label for="subscribeNews">Piscines</label>
                <br>
                <input type="checkbox" id="piscine" name="piscine" value="piscine">
                <label for="subscribeNews">Parkings</label>
              </mat-menu>
          </div>
      </div>

      <div id="map" class="map"></div>
          <div id="popup" class="ol-popup">
            <a href="#" id="popup-closer" class="ol-popup-closer"></a>
            <div id="popup-content"></div>
          </div>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

在我的app.component.ts中,我有这段代码来检索复选框状态,但这不起作用(此代码在简单的HTML文件中有效)

app.component.ts:(提取)

$('#piscine').on('change', function() {
    var isChecked = $(this).is(':checked');
    if (isChecked) {
      this.map.addControl(this.vectorLayer_Piscine);
      this.vectorLayer_Piscine.setStyle(piscine);
      this.map.addOverlay(popup);
    } else {
      this.map.removeControl(this.vectorLayer_Piscine);
      this.map.removeOverlay(popup);
    }
  });

  $('#parking').on('change', function() {
    var isChecked = $(this).is(':checked');
    if (isChecked) {
      this.map.addControl(this.vectorLayer_Parking);
      this.vectorLayer_Parking.setStyle(markers);
      this.map.addOverlay(popup);
    } else {
      this.map.removeControl(this.vectorLayer_Parking);
      this.map.removeOverlay(popup);
    }
  });
Run Code Online (Sandbox Code Playgroud)

通过jQuery的导入:(import $ from 'jquery';我用过npm install jquery

使用此代码,我只想在选中相应的复选框时才在地图上显示一些标记。

还有另一种方法来检索复选框状态吗?

Pad*_*han 5

首先我可以看到两个

<input type="checkbox" id="piscine" name="piscine" value="piscine">
Run Code Online (Sandbox Code Playgroud)

在您的代码中。请更正(ID和名称相同)。

接下来是不需要value属性。去掉它。

然后做如下

<input type="checkbox" id="piscine" name="piscine" (change)="handleSelected($event)">
Run Code Online (Sandbox Code Playgroud)

在ts文件中

handleSelected($event) {
   if ($event.target.checked === true) {
   // Handle your code
   }
}
Run Code Online (Sandbox Code Playgroud)

希望能帮到你!