Error typeerror cannot read properties of undefined reading nativeelement

I'm submitting a ... (check one with "x") [X ] bug report => search github for a similar issue or PR before submitting [ ] feature request [ ] support request => Please do not s...

@nethore

I’m submitting a … (check one with «x»)

[X ] bug report => search github for a similar issue or PR before submitting
[ ] feature request
[ ] support request => Please do not submit support request here

Current behavior
I’m using the latest version of ngx-charts with Angular 4.0.0 and I get an error when trying to set view to undefined to get the chart at parent’s div dimensions.

ChartWindowComponent.html:52 ERROR TypeError: Cannot read property 'nativeElement' of undefined at LineChartComponent../src/common/base-chart.component.ts.BaseChartComponent.getContainerDims (index.js:9031) at LineChartComponent../src/common/base-chart.component.ts.BaseChartComponent.update (index.js:9015) at LineChartComponent../src/line-chart/line-chart.component.ts.LineChartComponent.update (index.js:14596) at LineChartComponent../src/common/base-chart.component.ts.BaseChartComponent.ngOnChanges (index.js:9004)

Expected behavior
Just get the chart to fit to the parent container size.

  • ngx-charts version: 5.1.2
  • Angular version: 4.0.0

@marjan-georgiev

@nethore

I can’t for now reproduce the issue on plunker (I’m trying but i can’t get the same error).
I don’t know why it isn’t working in my project but it’s working in the demo. It might be because my div’s structure is a bit complexe and I don’t know why in this line, chartElement seems to be undefined :
var hostElem = this.chartElement.nativeElement;
It’s like it cannot init this.chartElement.

The complete error is :
capture d ecran 2017-05-10 a 09 46 14

If you have any idea where it could come from, I’m running out of ideas about the issue’s origin.

@GallinEnerg

Hi Guys’ I am having the same issue. The strange thing it that when I load and run ngx-charts as a separate project ie through the main app component it works as expected. I run into this issue after incorporating ngx-charts into my project through it’s own component?
I also can’t replicate the error on plunker?

@GallinEnerg

Hi There you can solve your issue by doing the following: In your chart component.html file, just change [results]=”single” to [result]=”SINGLE”.

From: Huiguang Liang [mailto:notifications@github.com]
Sent: 17 May 2017 08:16
To: swimlane/ngx-charts <ngx-charts@noreply.github.com>
Cc: Gary Allin <gary.allin@energ.co.uk>; Comment <comment@noreply.github.com>
Subject: Re: [swimlane/ngx-charts] Cannot read property ‘nativeElement’ of undefined when View is undefined (#374)

Hi, I have a very similar issue. The demo example provided works fine, but once I try to incorporate ngx-charts like this: Plunker<https://plnkr.co/edit/Yp77lIum7EaYV4c8hjQ0?p=preview>, a whole bunch of Cannot read property ‘<whatever>’ of undefined is thrown.


You are receiving this because you commented.
Reply to this email directly, view it on GitHub<#374 (comment)>, or mute the thread<https://github.com/notifications/unsubscribe-auth/AXk0lmZYMF9Od6KrRunn4tEf42boW8Gpks5r6p63gaJpZM4NR0sf>.

Disclaimer

The information contained in this communication from the sender is confidential. It is intended solely for use by the recipient and others authorized to receive it. If you are not the recipient, you are hereby notified that any disclosure, copying, distribution or taking action in relation of the contents of this information is strictly prohibited and may be unlawful.

This email has been scanned for viruses and malware, and may have been automatically archived by Mimecast Ltd, an innovator in Software as a Service (SaaS) for business. Providing a safer and more useful place for your human generated data. Specializing in; Security, archiving and compliance. To find out more visit the Mimecast website.

@huiguang-liang

Yeah I realized it was my error so I deleted my comment, cheers

On May 17, 2017 20:00, «GallinEnerg» ***@***.***> wrote:
Hi There you can solve your issue by doing the following: In your chart
component.html file, just change [results]=”single” to [result]=”SINGLE”.

From: Huiguang Liang ***@***.***
Sent: 17 May 2017 08:16
To: swimlane/ngx-charts ***@***.***>
Cc: Gary Allin ***@***.***>; Comment <
***@***.***>
Subject: Re: [swimlane/ngx-charts] Cannot read property ‘nativeElement’ of
undefined when View is undefined (#374)

Hi, I have a very similar issue. The demo example provided works fine, but
once I try to incorporate ngx-charts like this: Plunker<
https://plnkr.co/edit/Yp77lIum7EaYV4c8hjQ0?p=preview>, a whole bunch of
Cannot read property ‘<whatever>’ of undefined is thrown.


You are receiving this because you commented.
Reply to this email directly, view it on GitHub<https://github.com/
swimlane/ngx-charts#374#issuecomment-302006515>, or mute the
thread<https://github.com/notifications/unsubscribe-auth/
AXk0lmZYMF9Od6KrRunn4tEf42boW8Gpks5r6p63gaJpZM4NR0sf>.

Disclaimer

The information contained in this communication from the sender is
confidential. It is intended solely for use by the recipient and others
authorized to receive it. If you are not the recipient, you are hereby
notified that any disclosure, copying, distribution or taking action in
relation of the contents of this information is strictly prohibited and may
be unlawful.

This email has been scanned for viruses and malware, and may have been
automatically archived by Mimecast Ltd, an innovator in Software as a
Service (SaaS) for business. Providing a safer and more useful place for
your human generated data. Specializing in; Security, archiving and
compliance. To find out more visit the Mimecast website.


You are receiving this because you commented.
Reply to this email directly, view it on GitHub
<#374 (comment)>,
or mute the thread
<https://github.com/notifications/unsubscribe-auth/AD6L8thr2GeFalFTyG_BPixD1vXoRo2Qks5r6uFpgaJpZM4NR0sf>
.

@marjan-georgiev

If you can’t reproduce in a plunkr, try creating a basic project and upload it to a public github repo where it can be reproduced.

@michal-th

I’m experiencing exactly the same issue,

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'nativeElement' of undefined TypeError: Cannot read property 'nativeElement' of undefined at LineChartComponent../src/common/base-chart.component.ts.BaseChartComponent.getContainerDims

Looks like if [view]=»undefined» , this.chartElement is undefined in getContainerDims of BaseChartComponent.

@swimlane/ngx-charts@5.3.1

Ionic Framework: 3.0.1
Ionic App Scripts: 1.3.0
Angular Core: 4.0.0
Angular Compiler CLI: 4.0.0
Node: 7.8.0
OS Platform: Linux 4.4
Navigator Platform: Linux x86_64

@eduibrahim

No news? I’m having same problem only with Ionic projects,

@aboglioli

I thinks it’s a problem with @angular/material

@wa1gon

I am having the same issue. I am having problem in my SPA which works, but throws this error.

So I took copy and pasted the example from the material mat-select page into my sand box page and got the same error. So there must be something wrong else where. I don’t have a clue how to debug this.

Using Angular 5.0.0 and Mat 2.0.0-beta.10-4905443.
Stack Trace:

MatSelect.html:1 ERROR TypeError: Cannot read property 'nativeElement' of undefined
    at MatSelect._onFadeInDone (select.js:688)
    at Object.eval [as handleEvent] (MatSelect.html:1)
    at handleEvent (core.js:11166)
    at callWithDebugContext (core.js:12592)
    at Object.debugHandleEvent [as handleEvent] (core.js:12232)
    at dispatchEvent (core.js:7878)
    at eval (core.js:8488)
    at _animationCallbacksBuffer.forEach.tuple (animations.js:270)
    at Array.forEach (<anonymous>)
    at _zone.run (animations.js:268)
    at ZoneDelegate.invoke (zone.js:392)
    at Object.onInvoke (core.js:3864)
    at ZoneDelegate.invoke (zone.js:391)
    at Zone.run (zone.js:142)
    at NgZone.run (core.js:3754)
    at Promise.resolve.then (animations.js:267)
    at ZoneDelegate.invoke (zone.js:392)
    at Zone.run (zone.js:142)
    at eval (zone.js:873)
    at ZoneDelegate.invokeTask (zone.js:425)
    at Zone.runTask (zone.js:192)
    at drainMicroTaskQueue (zone.js:602)
    at ZoneTask.invokeTask [as invoke] (zone.js:503)
    at invokeTask (zone.js:1540)
    at HTMLElement.globalZoneAwareCallback (zone.js:1566)

Any suggestions would be welcome.

@wa1gon

Problem went away after I imported material. Then I removed the import without any issue.
Strange.

@caotuiit1997

I don’t know if you guy had resolved this issue: MatSelect.html:1 ERROR TypeError: Cannot read property ‘nativeElement’ of undefined.
I found a solution by setTimeOut and waited for all view init.

ngAfterViewInit() {
    setTimeout(()=>{
      this.loadingMap = true;
      if (this.loadingMap == true) {
        this.loadMap();
      }
    },3000);
  }

It worked for me perfectly!

@marjan-georgiev

Closing this as a potential solution has been provided above. If the problem still occurs and an example of it can be provided, I would be happy to reopen.

@samusonak

I am still having this problem, Getting
RROR Error: Uncaught (in promise): TypeError: Cannot read property ‘nativeElement’ of undefined
TypeError: Cannot read property ‘nativeElement’ of undefined
at ReportPage.Array.concat.ReportPage.createBarChart (report.ts:97)

@suchetaswabhav

I still get this error while downloading the PDF —

app.component.ts
`

export class PayloadComponent implements OnInit, AfterViewInit {
 ngOnInit() {

this.payloadLogKey = this.shareData.LOG_KEY_VALUE_3;

console.log("inside payload KEY_VALUE = " + this.payloadLogKey);

  }

  ngAfterViewInit(){

  setTimeout(()=>{
    this.loading = true;
    if (this.loading == true) {
      this.viewPayloadTransaction();
    }
     },3000);

   }

   @ViewChild('content')content : ElementRef;


  public downloadPDF(){

console.log ("inside downloadPDF()")
let doc = new jsPDF();

doc.setFontSize(45);

doc.setLineWidth(18.5);
doc.setFont("courier");

  let specialElementHandlers = {

  '#editor':function (element,renderer){
  return true;
  }
 };

 let content = this.content.nativeElement;
 doc.fromHTML(content.innerHTML,10,10,{

 'width' : 120,
 'elementHandlers':specialElementHandlers

 });
console.log("2nd inside download pdf",this.content )

console.log("3rd inside download pdf ", this.content )

 doc.setLineWidth(1);
 doc.save('payload.pdf');

  }
  }

`

app.component.html

<td type="text" title="{{dat.PAYLOAD}}" > <span class="fa fa-file-pdf-o" title="Copy to PDF" id= "downloadPdf" (click)="downloadPDF()" style="font-size:20px; "></span> &nbsp;&nbsp; <span class="glyphicon glyphicon-duplicate" id="downloadToClipboard" title="Copy to Clipboard" (click)="jqFn(dat)" style="font-size:10px; cursor:pointer"></span>&nbsp;&nbsp; {{dat.PAYLOAD|slice:0:12}} </td>

Error

TypeError: Cannot read property ‘nativeElement’ of undefined
at PayloadComponent.downloadPDF (payload.component.ts:160)
at Object.eval [as handleEvent] (PayloadComponent.html:193)
at handleEvent (core.es5.js:11997)
at callWithDebugContext (core.es5.js:13458)
at Object.debugHandleEvent [as handleEvent] (core.es5.js:13046)
at dispatchEvent (core.es5.js:8601)
at eval (core.es5.js:9212)
at HTMLSpanElement.eval (platform-browser.es5.js:2651)
at ZoneDelegate.invokeTask (zone.js:424)
at Object.onInvokeTask (core.es5.js:3881)

@hardik-godhani

i just a timeout of 300 ms and its works.

@devangptechuz

you should use ngAfterviewInit(){ } instead of timeout()

@ammad172

you should use ngAfterviewInit(){ } instead of timeout()

I have tried this as well not working and giving same error

@howtomake

hi

if develop mode its ok, but after build project i have
ERROR TypeError: Cannot read property 'nativeElement' of undefined

@erickroac

Hi!

I had the same problem when I tried to use ‘ @ViewChild(‘searchInput’, {static: true}) public searchElementRef: ElementRef;’ and I wasted a lot of time looking for a solution, but the only problem there was that I had my input inside an ng-template, so when the page loaded it seemed that the content was hidden I could not render the element, based on my hypothesis I took the input to the main page of the HTML and boom! The error went away, but I did not stay there, I put the element inside a div and use ngIF and initialized it to false, and I had the error again, it seems that when starting the hidden element it does not recognize it, oh and by the way, If the content is hidden and then you show it and then try to call the function, it still doesn’t work, I hope my experience helps you.

This tutorial guides you on how to resolve @ContentChild TypeError: : Cannot read property ‘nativeElement’ of undefined error that you are facing in Angular.

When I was trying access to ng-content with @ContentChild I got the following error : Cannot read property ‘nativeElement’ of undefined.

ERROR TypeError: Cannot read property 'nativeElement' of undefined
    at ItemElementComponent.push../src/app/item-element/item-element.component.ts.ItemElementComponent.ngOnInit (item-element.component.ts:54)
    at callHook (core.js:2970)
    at callHooks (core.js:2940)
    at executeInitAndCheckHooks (core.js:2892)
    at selectIndexInternal (core.js:6331)
    at ɵɵadvance (core.js:6304)
    at AppComponent_app_item_element_9_Template (template.html:31)
    at executeTemplate (core.js:7757)
    at refreshView (core.js:7626)
    at refreshEmbeddedViews (core.js:8726)

Here is the code that I tried accessing ng-content with @ContentChild which resulted in above error. In App Component placed the local reference “#contentParagraph” on the pragraph.

app.component.html

<div class="container">
  <app-create-item (itemAdded)="onItemAdded($event)"
                   (itemSpecAdded)="onItemSpecAdded($event)"></app-create-item>
  <hr>
  <div class="row">
    <div class="col-xs-12">
      <button class="btn btn-primary" (click)="onChangeComponentElement()">Change item element</button>
      <!-- To Demo ngOnDestroy() -->
      <button class="btn btn-danger" (click)="onDestroyComponentElement()"> Destroy component</button>
      <app-item-element *ngFor="let elem of itemElems"
                        [itemElem] = "elem"
                        [title] = "elem.title">
                        <!-- projecting content into component with ng-content -->
                        <p #contentParagraph>
                          <strong *ngIf="elem.type === 'item'" style="color: orange">{{ elem.desc }}</strong>
                          <em *ngIf="elem.type === 'spec'">{{ elem.spec }}</em>
                        </p>
      </app-item-element>

    </div>
  </div>
</div>

Then, accessed the template reference variable “#contentParagraph” in our ItemElementComponent class using @ContentChild as shown below.

item-element.component.ts

import { 
  AfterViewChecked,
  AfterViewInit,
  AfterContentChecked,
  AfterContentInit,
  Component, 
  DoCheck, 
  Input, 
  OnChanges, 
  OnInit, 
  SimpleChanges,
  OnDestroy,
  ElementRef,
  ContentChild
} from '@angular/core';

@Component({
  selector: 'app-item-element',
  templateUrl: './item-element.component.html',
  styleUrls: ['./item-element.component.css'],
  
})

export class ItemElementComponent implements OnInit, OnChanges, DoCheck, AfterContentInit, AfterContentChecked, AfterViewInit, AfterViewChecked, OnDestroy{

  @Input() itemElem : {type: string, title: string, desc: string, spec: string};
  @Input() title : string;
  @ContentChild('contentParagraph') paragraph : ElementRef;
  
  constructor() {
    console.log("constructor called.....");
  }

  ngOnChanges(changes: SimpleChanges) {
    console.log("ngOnChanges called.....");
    console.log(changes);
  }

  ngOnInit(): void {
    console.log("ngOnInit called.....");
    console.log('Paragraph text Content:' + this.paragraph.nativeElement.textContent);
  }

  ngDoCheck(){
    console.log("ngDoCheck called.....");
  }

  ngAfterContentInit(){
    console.log("ngAfterContentInit called.....");
    
  }

  ngAfterContentChecked(){
    console.log("ngAfterContentChecked called.....");
  }

  ngAfterViewInit(){
    console.log("ngAfterViewInit called.....");
  }

  ngAfterViewChecked(){
    console.log("ngAfterViewChecked called.....");
  }

  ngOnDestroy(){
    console.log("ngOnDestroy called.....");
  }

}

While running Angular application with above code changes I got ERROR TypeError: Cannot read property ‘nativeElement’ of undefined.

After referring angular docs I understood that from Angular 8+, the @ContentChild syntax have been changed slightly as shown below.

Instead of:

@ContentChild('contentParagraph') paragraph: ElementRef;

Should use

@ContentChild('contentParagraph', {static: true}) paragraph: ElementRef;

Note, you need to add {static: true} as a second argument, if you are planning to access the selected element inside of ngOnInit(). And if you don’t access the selected element in ngOnInit(), but elsewhere in your component the set {static: false} instead.

Also, note if you are using Angular 9+, you need to add {static:true}  if needed, but not {static:false}

Of course, you can’t access the value “paragraph” of before you reach ngAfterContentInit() as shown below***.

item-element.component.ts:43 constructor called.....
item-element.component.ts:47 ngOnChanges called.....
item-element.component.ts:48 {itemElem: SimpleChange, title: SimpleChange}
item-element.component.ts:52 ngOnInit called.....
***item-element.component.ts:53 Header Content:
***item-element.component.ts:54 Paragraph text Content:
item-element.component.ts:58 ngDoCheck called.....
item-element.component.ts:62 ngAfterContentInit called.....
***item-element.component.ts:63 Paragraph text Content:Android phone by Google

Therefore, after adding second argument {static: true} , the error TypeError: : Cannot read property ‘nativeElement’ of undefined while using @ContentChild is gone away.

Hope it helped 🙂

  • Call ngOnInit() again from another function – Angular 9 ?
  • ngOnChanges get new value and previous value – Angular
  • Why do we need ngDoCheck lifecycle hook – Angular ?
  • Global Angular CLI version is greater than your local version
  • Upgrade Angular CLI to the latest version Angular 9 or 10 ?
  • ViewEncapsulation modes and differences
  • How to use new static option in ViewChild Angular 9 ?
  • Project contents into angular components using ng-content
  • Call ngOnInit() again from another function – Angular 9 ?
  • How to access ng-content with @ContentChild – Angular Component ?
  • How Angular Encapsulates Styles using ViewEncapsulation ?
  • ngAfterViewInit with Example – Angular
  • ngAfterContentChecked with Example
  • ngOnDestroy Example Angular
  • Angular Component : In which lifecycle hook you can check value of DOM element ?

References:

  • Angular docs
  • ContentChild

The TypeError: Cannot read property of undefined is one of the most common type errors in JavaScript. It occurs when a property is read or a function is called on an undefined variable.

Install the JavaScript SDK to identify and fix these undefined errors

Error message:

TypeError: Cannot read properties of undefined (reading x)

Error type:

TypeError

What Causes TypeError: Cannot Read Property of Undefined

Undefined means that a variable has been declared but has not been assigned a value.

In JavaScript, properties and functions can only belong to objects. Since undefined is not an object type, calling a function or a property on such a variable causes the TypeError: Cannot read property of undefined.

TypeError: Cannot Read Property of Undefined Example

Here’s an example of a JavaScript TypeError: Cannot read property of undefined thrown when a property is attempted to be read on an undefined variable:

function myFunc(a) {
console.log(a.b);
}

var myVar;
myFunc(myVar);

Since the variable myVar is declared but not initialized, it is undefined. When it is passed to the myFunc function, the property b is attempted to be accessed. Since a is undefined at that point, running the code causes the following error:

TypeError: Cannot read properties of undefined (reading 'b')

How to Avoid TypeError: Cannot Read Property of Undefined

When such an error is encountered, it should be ensured that the variable causing the error is assigned a value:

function myFunc(a) {
    console.log(a.b);
}

var myVar = {
    b: 'myProperty'
};

myFunc(myVar);

In the above example, the myVar variable is initialized as an object with a property b that is a string. The above code runs successfully and produces the following output on the browser console:

myProperty

To avoid coming across situations where undefined variables may be accessed accidentally, an if check should be added before dealing with such variables:

if (myVar !== undefined) {
    ...
}

if (typeof(myVar) !== 'undefined') {
    ...
}

Updating the previous example to include an if check:

function myFunc(a) {
    if (a !== undefined) {
        console.log(a.b);
    }
}

var myVar;
myFunc(myVar);

Running the above code avoids the error since the property b is only accessed if a is not undefined.

Here is how you can handle errors using a try { } catch (e) { } block.

// Caught errors
try {

  //Place your code inside this try, catch block
  //Any error can now be caught and managed

} catch (e) {
  Rollbar.error("Something went wrong", e);
  console.log("Something went wrong", e);
}

Here is how you can setup a JavaScript Error handler: Setup JavaScript Error Handler

Where TypeError Resides in the JavaScript Exception Hierarchy

JavaScript provides a number of core objects that allow for simple exception and error management. Error handling is typically done through the generic Error object or from a number of built-in core error objects, shown below:

  • Error
  • InternalError
  • RangeError
  • ReferenceError
  • SyntaxError
  • TypeError
    • Cannot read property of undefined

As seen from the hierarchy above, TypeError is a built-in JavaScript error object that allows for the administration of such errors. The “Cannot read property of undefined” TypeError is a descendant of the TypeError object.

Track, Analyze and Manage Errors With Rollbar

Rollbar in action

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing JavaScript errors easier than ever. Sign Up Today!

У меня проблема с использованием @ViewChild () в моем приложении Ionic 3. Действительно, я хотел бы иметь возможность отображать карту на втором сегменте моей страницы. И у меня следующая ошибка:

ERROR TypeError: Cannot read property 'nativeElement' of undefined

Вот мой HTML-код:

<ion-header>
    <ion-navbar>
        <ion-title>Favoris</ion-title>
    </ion-navbar>
    <div padding>
        <ion-segment [(ngModel)]="view">
            <ion-segment-button value="list">
                Liste
            </ion-segment-button>
            <ion-segment-button value="map">
                Carte
            </ion-segment-button>
        </ion-segment>
    </div>
</ion-header>

<ion-content>
    <div [ngSwitch]="view">
        <div *ngSwitchCase="'list'">
            <ion-card *ngFor="let favorite of favorites">
                <img src="{{ favorite.photo }}" />
                <ion-card-content>
                    <ion-card-title>
                        {{ favorite.name }}
                        <ion-icon name="trash" class="icon-remove" (click)="removeFavorite(favorite.id_place)"></ion-icon>
                    </ion-card-title>
                    <p>
                        {{ favorite.address }}
                    </p>
                </ion-card-content>
            </ion-card>
        </div>

        <div *ngSwitchCase="'map'">
            <div #map id="map" class="map"></div>
        </div>
    </div>
</ion-content>

Вот мой код TS:

import { Component, ViewChild, ElementRef } from '@angular/core';
import { IonicPage, NavController } from 'ionic-angular';
import { AngularFireAuth } from "angularfire2/auth";

import { GoogleMapsProvider } from './../../providers/google-maps/google-maps';

declare var google: any;

@IonicPage()
@Component({
    selector: 'page-favorite',
    templateUrl: 'favorite.html'
})
export class FavoritePage {
    @ViewChild('map') mapRef: ElementRef;
    map: any;
    lat: string;
    lng: string;
    view: string = "list";
    /**
     * a MODIFIER AVEC l'API
     */
    favorites: { id_place: string, name: string, photo: string, address: string }[] = [
        { "id_place" : "9054b4cc53b207424db12d23e1b34b3ae0cfe9c0",  "name": "Café Madeleine Paris", "photo": "https://lh3.googleusercontent.com/p/AF1QipMkeDY6tB5bQFEPhy1Ah4HR-2Oh7CjO_td-BbDY=s1600-w400", "address": "1 Rue Tronchet, Paris" },
        { "id_place" : "cf49d5cbc84ecbe0388ef93eb80aa18f9db3ffa9", "name": "Cafe Kitsune", "photo": "https://lh3.googleusercontent.com/p/AF1QipNk8GqMTGNo-QF_QwdakFaNvoGwi11tHmY-969p=s1600-w400", "address": "1 Rue Tronchet, Paris" },
        { "id_place" : "b8c6ecc9f9e047dd428f3994c537c3f877ba0e30", "name": "Café des Abattoirs", "photo": "https://lh3.googleusercontent.com/p/AF1QipPRKYf0L3uEYzPee5Y7uUBa15Q_7WWtUTWSHvqd=s1600-w400", "address": "10 Rue Gomboust, Paris" },
    ];


    constructor(
        private aFAuth: AngularFireAuth,
        public navCtrl: NavController,
        public GoogleMaps: GoogleMapsProvider,
    ) {

    }


    ionViewDidLoad() {
        this.showMapWithMarker();
    }

    showMapWithMarker() {
        const location = new google.maps.LatLng(-25.363, 131.044);
        const options = {
            center: location,
            zoom: 20
        };
        this.map = new google.maps.Map(this.mapRef.nativeElement, options);

        var marker = new google.maps.Marker({
            position: location,
            title: 'hello world',
            animation: google.maps.Animation.DROP
        });

        // To add the marker to the map, call setMap();
        marker.setMap(this.map);
    }

    removeFavorite(id_place) {
        console.log('Remove favorite : ', id_place)
    }
}

Вы знаете, как я могу исправить эту проблему?

Спасибо заранее за вашу помощь.

2 ответа

Лучший ответ

1. когда ваша страница загружена, значение представления — ‘list’, карта элементов не может отображаться на вашей странице. Поэтому mapRef имеет значение null,

2. вопрос — ngSwitchCase, когда значение ngSwitch не может соответствовать ngSwitchCase, элемент не будет отображаться.

3. возможно, вы можете использовать директиву [скрытый]
<div [hidden]="view!='list'"> </div>
<div [hidden]="view!='map'"> </div>


0

Eric Zeng
13 Июл 2018 в 17:45

Начальное значение view не соответствует регистру, который проверяет, нужно ли отображать div карты.

view: string = "list"; // it should be "map"

<div *ngSwitchCase="'map'">
     <div #map id="map" class="map"></div>
</div>


0

Hikmat G.
13 Июл 2018 в 16:52

Понравилась статья? Поделить с друзьями:
  • Error typeerror cannot read properties of undefined reading length
  • Error typed files cannot contain reference counted types
  • Error typecheck offendingcommand show
  • Error typecheck offendingcommand makefont
  • Error typecheck offending command setdash