Pitiwat Rakprommarat
Pitiwat Rakprommarat

Reputation: 15

Angular5 Instascan - Open Camera Not Working <video>

Angular5 - Instascan - Show Camera View (video tag) Not Working. But my camera is open.


app.component.ts

constructor(){    
this.Instascan= require('instascan'); 

let scanner = new this.Instascan.Scanner({ video: document.getElementById("preview") });

scanner.addListener('scan', function (content) {
  console.log(content);
});
this.Instascan.Camera.getCameras().then(function (cameras) {
  if (cameras.length > 0) {
    scanner.start(cameras[0]);
  } else {
    console.error('No cameras found.');
  }
}).catch(function (e) {
  console.error(e);
});
}

app.component.html

<video id="preview"></video>

Instascan --- https://github.com/schmich/instascan

Upvotes: 0

Views: 1273

Answers (1)

Lazar Ljubenović
Lazar Ljubenović

Reputation: 19754

let scanner = new this.Instascan.Scanner({ video: document.getElementById("preview") });

The problem is that you're executing the above code in the constructor, when view has no been initialized yet. document.getElementById("preview") will return null because no elements are found at this moment. Hence, the thing you're trying to use it never correctly initialized.

You should run that code in Angular's AfterViewInit hook. Also, you should use ViewChild decorator to grab the ElementRef instead of using document. It's against good practice to access DOM like you're doing here.

Upvotes: 1

Related Questions