0

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>

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, just check the event if it's not undefined. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.