Hoàng Nguyễn
Hoàng Nguyễn

Reputation: 1170

Angular 5 Cannot read property 'target' of undefined

I embed a chart widget and want to render the chart dynamically by passing value from a dropdown menu into the chart's symbol as data reference. The app works, but the console log shows the error right from initializing the view.

Here is my code:

Component:

export class TradeChartComponent implements OnInit, AfterViewInit {

  @Output() emitValue: EventEmitter<string> = new EventEmitter<string>();

  selectedValue: any;

  constructor(
    private http: HttpClient,
    private apiService: ApiService,
    @Inject(PLATFORM_ID) private platformId: Object
  ) {}

  selectPair(pair) {
    // tslint:disable-next-line:no-unused-expression
    const widget = new TradingView.widget({
      'container_id': 'technical-analysis',
      'autosize': true,
      'symbol': pair,
      'interval': '120',
    });
  }

  onChange(event: any) {
    const widget = this.selectPair(event.target.value);
    this.emitValue.emit(this.selectedValue);
  }

  ngOnInit() {
    this.selectPair('BTCUSD');
  }

  ngAfterViewInit() {
    this.onChange(event);
  }
}

View:

<select (change)="onChange($event)" class="form-control" [(ngModel)]="selectedValue">
    <option value="BTCUSD">BTC/USD</option>
    <option value="ETHUSD">ETH/USD</option>
</select>

<div id="technical-analysis" style="height: 280px"></div>

Upvotes: 0

Views: 5551

Answers (1)

user4676340
user4676340

Reputation:

Cannot read property 'target' of undefined

Means the object you use doesn't have a target property.

Let's search in your code for a target usage :

const widget = this.selectPair(event.target.value);

This means you have an empty event object.

You said it happens when you load the component ? Then let's look into your constructor and lifecycle hooks :

  ngAfterViewInit() { this.onChange(event); }

Here you go : you are passing an non-existing event to your function, making it throw an error. Where does this event comes from ? Your IDE should warn you that it is not existing.

Simply delete this line, or test if your event isn't null, and your error will resolve itself.

Upvotes: 2

Related Questions