cfoster5
cfoster5

Reputation: 1826

Check aspect ratio of image from ngModel

Using Angular 5 and Bootstrap, I have created a form that allows users to link an image with a URL. I'd like to restrict this image to have a specific aspect ratio.

This is my input for the ngModel smallimagelink. I am using this form to generate a preview before the item is submitted.

Here is the HTML and here is a functioning demo.

<div class="col-md-6 mb-3">
  <label for="smallimagelink">Small image link (used if review will not be a feature)</label>
  <input type="text" class="form-control" placeholder="" value="" required name="smallimagelink" [(ngModel)]="smallimagelink">
</div>

<div class="card flex-md-row mb-4 box-shadow h-md-250">
  <img class="card-img-right flex-auto d-none d-md-block" src="{{smallimagelink}}" alt="Card image cap">
</div>

When the input has been filled in with a correct URL, the preview properly displays. However, I'd like to be able to check the image being referenced in the src in the preview with Angular / JavaScript.

How can I do this?

Upvotes: 1

Views: 1342

Answers (1)

kshetline
kshetline

Reputation: 13734

You can mark your image like this:

<img #smallImage class="card-img-right flex-auto d-none d-md-block" src="{{smallimagelink}}" alt="Card image cap">

...so that it has a name that you can refer to it as a ViewChild of your AppComponent like this:

@ViewChild('smallImage') private smallImageRef: ElementRef;

Then go from there to get at the nativeElement and attached a listener to its onload method. I'll play around with your stackblitz some more and see how that goes.

Actually, you can do without the @ViewChild thing and do something like this:

<div class="col-md-6 mb-3">
  <label for="smallimagelink">Small image link (used if review will not be a feature)</label>
  <input type="text" class="form-control" placeholder="" value="" required name="smallimagelink" [(ngModel)]="smallimagelink">
</div>

<div class="card flex-md-row mb-4 box-shadow h-md-250">
  <img class="card-img-right flex-auto d-none d-md-block" src="{{smallimagelink}}" alt="Card image cap" (load)="onLoad($event)" (error)="onError()">
  <p>{{imageWidth}}, {{imageHeight}}</p>
</div>

-

import { Component, ElementRef } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent {
  name = 'Angular 5';
  imageWidth = '-';
  imageHeight = '-';

  onLoad(event: Event) {
    const smallImage = event.target as HTMLImageElement;
    this.imageWidth = String(smallImage.width);
    this.imageHeight = String(smallImage.height);
  };

  onError() {
    this.imageWidth = '-';
    this.imageHeight = '-';
  };
}

The above just updates the display with the width and height of the selected image, but it's a starting point for doing whatever you want with the aspect ratio.

https://stackblitz.com/edit/angular-hiq9qa

Upvotes: 2

Related Questions