错误TS2339:类型'HTMLElement'上不存在属性'imageID'

时间:2018-04-04 16:17:11

标签: javascript typescript

尝试使用全局变量 imageID 来获取getImage的值,但不断收到错误“属性'imageID'在类型'HTMLElement'上不存在。” 。 想要将HTMLELement分配给全局变量 imageID 。有没有办法将变量解析为字符串或其他什么? 任何建议,将不胜感激。

dashboard.component.ts

 import {Component,Input,OnChanges,OnInit,SimpleChanges} from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import {Emotion} from 'emotion';
import {EmotionService} from 'emotion.service';



@Component({
    selector: 'dashboard',
    templateUrl: './dashboard.component.html',
    styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
    emotions: Emotion[] = [];
    emotion: string;
    imageID: any;
    constructor(private emotionService: EmotionService) {}

    ngOnInit() {
        this.getEmotions();
       // this.makeMatch();

        //function to randomize and get face images
        var w = document.getElementById('wrapper');
        var button = document.getElementById('randomize');
        var images = w.children; // inner elements, your image divs
        // a function to hide all divs
        var hideDivs = function(imgs: HTMLCollection) {
            for (var img of < any > imgs) {
                (img as HTMLElement).style.display = 'none';
            } //for
        } //hideDivs

        hideDivs(images); // hide all initially

        button.addEventListener('click', function(event) {
            console.log('');
            console.log('%c=============================', "color: blue");
            console.log('%c In getFaces method', "color: blue", );
            var rnd = Math.floor(Math.random() * images.length); // get random index
            hideDivs(images); // hide all images

            (images[rnd] as HTMLElement).style.display = 'block'; // show random image
            (event.target as HTMLElement).textContent = 'Click one more time!';
            var getImage = (images[rnd] as HTMLElement);


                    //where error occurs
           this.imageID = getImage.id;


            // this.imageID as HTMLElement = images[rnd].getAttribute('alt');
              console.log('%c Image ID for match making: ', imageID );
            console.log('%cImage ID: ', "font-weight: bold", getImage.id);
           // console.log('%cAll image data:', "font-weight: bold", images[rnd]);
            console.log('%c=============================', "color: blue");
            console.log('');

        }) //button

1 个答案:

答案 0 :(得分:1)

发生错误是因为代码中的这个===按钮

button.addEventListener('click', function(event) {
       ...
       this.imageID = getImage.id;
       ...
    })

如果你想将imageID写成全局变量,只需使用窗口

window.imageID = getImage.id;

如果要将imageID写入类实例属性,请使用bind

button.addEventListener('click', function(event) {
       ...
       this.imageID = getImage.id;
       ...
    }.bind(this))

或箭头功能

button.addEventListener('click',(event) => {
       ...
       this.imageID = getImage.id;
       ...
    })