Search code examples
javascripttypescriptionic-frameworkangular-ngmodel

Ionic 3 set value in html template


I am trying to set a value in an Ionic 3 template from my ts file, however I am also appending css to it at the same time. I am getting this error

ERROR

Error: Uncaught (in promise): Error: No value accessor for form control with name: 'image' Error: No value accessor for form control with name: 'image'

My code is a s follows.

HTML

<img name="image" [(ngModel)]="image" id="image" src="https://openclipart.org/image/2400px/svg_to_png/247149/dual-compass-rose.png" alt=""> 

TS

this.image.style.transform = 'rotate(' + this.magneticHeading + 'deg)';

I am not sure why this is not working but am starting to think that angular doesn't like what I'm trying to do in the TS file by .style.transform...


Solution

  • Use @ViewChild to reference image tag from your DOM. Use [src] and not ngModel:

    Typescript:

      @ViewChild('myImage') myImage;
      magneticHeading = '100';
      image="https://openclipart.org/image/2400px/svg_to_png/247149/dual-compass-rose.png"
      ...
      ngAfterViewInit() {
        this.myImage.nativeElement.style.transform = 'rotate(' + this.magneticHeading + 'deg)';
      }
    

    HTML:

      <img #myImage name="image" id="image" [src]="image" alt=""> 
    

    DEMO

    Or to set it from HTML:

      <img #myImage [style.transform]="'rotate(' + magneticHeading + 'deg)'" name="image" id="image" [src]="image" alt=""> 
    

    DEMO