错误TypeError:无法读取属性' nativeElement'未定义的角度5

时间:2018-06-06 04:14:24

标签: angular typescript

我知道我不是第一个问这个的人,但我确信我的问题与其他问题略有不同。

在我的应用程序中,一旦用户从mycart中删除产品,我想自动关闭模式。(点击mycart图标后会显示模态)。

我的代码正如我预期的那样工作,但我收到了控制台错误。

错误:

  

TypeError:无法读取属性' nativeElement'未定义的           在AppComponent.closeModalIfNoCart(app.component.ts:107)           在SafeSubscriber.eval [as _next](app.component.ts:100)           在SafeSubscriber .__ tryOrUnsub(Subscriber.js:240)           在SafeSubscriber.next(Subscriber.js:187)           在Subscriber._next(Subscriber.js:128)           在Subscriber.next(Subscriber.js:92)           在MapSubscriber._next(map.js:85)           在MapSubscriber.Subscriber.next(Subscriber.js:92)           在FilterSubscriber._next(filter.js:90)           在FilterSubscriber.Subscriber.next(Subscriber.js:92)

app.component.html

     <div *ngIf="mycart && mycart.length" class="modal fade modalstyle" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header headerHeight text-white " style="background:rgb(0, 0, 0);font-weight:bold">
        <h6 class="modal-title" id="exampleModalLabel">My Cart Items</h6>
        <button #closeModalBtn type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <div *ngFor="let products of mycart;let i =index;">
          <div class="container col-sm-12">
            <div class="row">
              <div class="col-sm-4 paddingforimage">
                <img [src]="products['ITEM_IMAGE_PATH']">
              </div>
              <div class="text-info col-sm-6">
                <span>
                  <h6>{{products?.TOTAL_QTY}} &times; {{products?.ITEM_PRICE}} &#8377;</h6>
                </span>
                <span>
                  <h6>{{products?.ITEM_DESC}}</h6>
                </span>
                <span>
                  <h6>{{products?.TOTAL_AMT}} &#8377;</h6>
                </span>
              </div>
              <div class="col-sm-1 text-right">
                <button type="button" class="close closebtn" aria-label="Close" (click)="detele_My_Cart(products?.ITEM_CODE)">
                  <span aria-hidden="true" (click)="detele_My_Cart(products?.ITEM_CODE)">&times;</span>
                </button>
              </div>
            </div>
          </div>
          <hr>
        </div>
        <div class=" container row col-sm-12">
          <div class="col-sm-6">
            <strong>SHIPPING</strong>
          </div>
          <div class="col-sm-6 text-right">0 &#8377;</div>
          <hr>
          <div class="col-sm-6">
            <strong>TOTAL</strong>
          </div>
          <div class="col-sm-6 text-right">{{my_Cart_Total_Amount}} &#8377;</div>
        </div>
        <br>
        <div class="container row col-sm-12" id="wrapper">
          <button type="button" class="btn btn-success buttonSize" data-dismiss="modal" routerLink="/cartsummary">
            <strong>CHECK OUT</strong>
          </button>
        </div>
      </div>
    </div>
  </div>
</div>

app.component.ts

import { Component, OnInit, ElementRef, ViewChild } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { DatePipe } from '@angular/common';
import { CartdataService } from './services/cartdata.service';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/observable/interval';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']


})
export class AppComponent implements OnInit {

  default_Cart_Count: number = 0;
  my_Cart_Total_Amount: number;
  mycart: any;
  my_Cart_Total_Amount1: number;
  mycartupdate: any;
  @ViewChild('closeModalBtn') closeModalBtn: ElementRef;

  constructor(private CartdataService: CartdataService, private http: HttpClient) { }

  ngOnInit() {
    // other codes
  }

  detele_My_Cart(item_Code: any) {
    this.publicIp.v4().then(ip => {
      this.CartdataService.delete_My_Cart(ip, item_Code).subscribe(
        data => {
          this.mycart = data['Table']
          this.my_Cart_Total_Amount = data['Table1'][0]['TOTAL_AMOUNT']

          this.closeModalIfNoCart();
        });
    });
  }

  closeModalIfNoCart() {
    if (!this.mycart || !this.mycart.length)
      this.closeModalBtn.nativeElement.click();
  }
}

的index.html

<!doctype html>
<html lang="en">

<head>

  <meta charset="utf-8">
  <title>ECommerceWebsite</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
    crossorigin="anonymous">
  <script defer src="https://use.fontawesome.com/releases/v5.0.6/js/all.js"></script>
  <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700" rel="stylesheet">

</head>

<body>

  <app-root></app-root>
  <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script><script>
    $('a[data-slide="prev"]').click(function () { $('#myCarousel').carousel('prev'); });
    $('a[data-slide="next"]').click(function () { $('#myCarousel').carousel('next'); });
  </script>

  <script>
    $('a[data-slide="prev"]').click(function () { $('#myCarousel1').carousel('prev'); });
    $('a[data-slide="next"]').click(function () { $('#myCarousel1').carousel('next'); });
  </script>

  <!-- <script>
    $(function () {
      $('#modal').modal(toggle)
    });
  </script> -->

  <script>
    $(document).ready(function () {
      $('#head__top').on('click', function () {
        $('#collapseExample').fadeToggle(300);
        $('#innerCollapse').hide();
      });
      $('#head__sub').on('click', function () {
        $('#innerCollapse').fadeToggle(300);
      });
    });
  </script>

</body>

</html>

角cli.json

"styles": [
        "../node_modules/bootstrap/dist/css/bootstrap.min.css",
        "styles.css"
      ],
      "scripts": [
        "../node_modules/jquery/dist/jquery.js",
        "../node_modules/bootstrap/dist/js/bootstrap.js"
      ]

的package.json

"dependencies": {
    "@agm/core": "^1.0.0-beta.2",
    "@angular/animations": "^5.2.0",
    "@angular/common": "^5.2.0",
    "@angular/compiler": "^5.2.0",
    "@angular/core": "^5.2.0",
    "@angular/forms": "^5.2.0",
    "@angular/http": "^5.2.0",
    "@angular/platform-browser": "^5.2.0",
    "@angular/platform-browser-dynamic": "^5.2.0",
    "@angular/router": "^5.2.0",
    "angular-web-storage": "^2.0.0",
    "angular-webstorage-service": "^1.0.2",
    "auth0-js": "^9.3.1",
    "bootstrap": "^4.1.1",
    "core-js": "^2.4.1",
    "dateformat": "^3.0.3",
    "jquery": "^3.3.1",
    "jquery.js": "0.0.2-security",
    "popper.js": "^1.14.3",
    "public-ip": "^2.4.0",
    "rxjs": "^5.5.6",
    "zone.js": "^0.8.19"
  }

图片:

enter image description here 我找不到我犯了错误。 任何人都可以帮我解决这个问题。

2 个答案:

答案 0 :(得分:0)

此错误可能是由于此代码*ngIf="mycart && mycart.length"

造成的

因此,当mycart.length等于0时,所有元素都将从DOM中删除。因此,您要么从HTML中删除此代码,要么使用以下代码替换。

[hidden]="!(mycart && mycart.length)"

答案 1 :(得分:-1)

你在哪里打detele_My_Cart?如果在ngOnInit中调用,则尚未定义closeModalBtn。它是在ngAfterViewInit方法之后定义的,如下所示:

enter image description here