0

hey guys I'm having some troubles with Angular. I have an array of objects and a couple of functions BUT in one of them the array is undefined. So there are my functions:

  • getTarget()
  • saveChanges()
  • addUser()
  • drawTable()
  • ngOnInit() I'm trying to console.log my array in all these functions, and everything is ok but getTarget() function! It's just keeping to log undefined into console while other functions' output is like (2) [Object, Object] Why is the array unreachable or what's worng?

This is my app code:

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

var ID:number;

export class entity {
    id:number;
    name:string;
    lName:string;
}


let USERS: entity[] = [
    {id: 0, name: 'Jon Smith', lName: 'Last Name'},
    {id: 1, name: 'qwe asd', lName: '123'}
];

@Component({
    selector: 'my-app',
    templateUrl: './template.html',
})

export class AppComponent implements OnInit{
    name = 'Angular';
    Users = USERS;

    /*deleteUser () {
        console.log(ID);
        delete this.Users[ID];
        this.drawTable();
    }*/
    getTarget() {
        let Target = event.target;
        let id = $(<HTMLButtonElement>Target).parent().parent().attr('id');
        console.log('номер',id);
        console.log(this.Users);
        ID = parseInt(id);
        //console.log($(<HTMLButtonElement>Target).text());
            if ($(<HTMLButtonElement>Target).text()=='Удалить'){
                /*this.Users = this.Users.slice(ID,1);
                this.drawTable();*/
                console.log(this.Users);
            }
    }
    saveChanges(id:number) {
        id = ID;
        $(<HTMLButtonElement>event.target).attr('data-dismiss', 'modal'); //Закрыть модальное окно
        $('#editErrorMessage').attr('style','visibility:hidden');//сделать сообщение об ошибке невидимым
            if (($('#editNameInput').val() != '' ) && ($('#editLNameInput').val()!='')) {
                this.Users[id].name = $('#editNameInput').val();//сохранить новые значения
                this.Users[id].lName = $('#editLNameInput').val();
                $('#editNameInput').val('');//очистить
                $('#editLNameInput').val('');//инпуты
                this.drawTable();
            }
            else {
                $(<HTMLButtonElement>event.target).removeAttr('data-dismiss');// не  закрывать модальное окно
                $('#editErrorMessage').removeAttr('style');//сообщение снова видно
            }
    }
    addUser() {
        $(<HTMLButtonElement>event.target).attr('data-dismiss', 'modal'); //Закрыть модальное окно
        $('#addErrorMessage').attr('style','visibility:hidden');//сделать сообщение об ошибке невидимым
        if (($('#addNameInput').val() != '' ) && ($('#addLNameInput').val() != '' ))
        {
            let tempObj:entity = {id: this.Users.length, name: $('#addNameInput').val(), lName: $('#addLNameInput').val()};
            this.Users.push(tempObj);
            $('#addNameInput').val('');
            $('#addLNameInput').val('');
            this.drawTable();
        }
        else {
            $(<HTMLButtonElement>event.target).removeAttr('data-dismiss');// не  закрывать модальное окно
            $('#addErrorMessage').removeAttr('style');//сообщение снова видно
        }
    }
    drawTable() {
        console.log('drawing', this.Users);
        let Table = $('table');
        let tBody = $('tbody');
        console.log(this.Users.length);
        tBody.empty();
        //элементы таблицы
            /*for (let rowIndex = 0; rowIndex == this.Users.length - 1; rowIndex++) {
                console.log(rowIndex);
                console.log(this.Users[rowIndex]);
                row.dataset.id = this.Users[rowIndex].id.toString(); // установить id строки
                    cell.innerHTML = this.Users[rowIndex].id.toString(); // текст внутри ячейки
                row.appendChild(cell); // добавить ячейку в ряд
                    cell.innerHTML = this.Users[rowIndex].name;
                row.appendChild(cell);
                    cell.innerHTML = this.Users[rowIndex].lName;
                row.appendChild(cell);
                    cell.innerHTML = ''; // убрать текст из ячейки
                        editButton.className = 'crud__DeleteEditButton form-control'; //настройка кнопки изменения
                        editButton.setAttribute('data-toggle', 'modal');
                        editButton.setAttribute('data-target', '#editModal');
                        editButton.setAttribute('onclick','getTarget()');
                        editButton.innerHTML = 'Изменить';
                    cell.appendChild(editButton); // добавить кнопку в ячейку
                row.appendChild(cell);
                        deleteButton.className = 'crud__DeleteEditButton form-control'; //настройка кнопки удаления
                        deleteButton.setAttribute('onclick','deleteUser()');
                        deleteButton.innerHTML = 'Удалить';
                    cell.appendChild(deleteButton);
                tBody.appendChild(row); //добавить строку в таблицу
            };*/
            for (let item of this.Users){
                console.log('start');
                let row = document.createElement('tr');
                let cells = [];
                let editButton = document.createElement('button');
                let deleteButton = document.createElement('button');
                    row.setAttribute('id',item.id.toString()) // установить id строки
                let cell1 = document.createElement('th');
                    cell1.innerHTML = item.toString(); // текст внутри ячейки
                    cells.push(cell1);
                console.log(cells);
                let cell2 = document.createElement('th');
                    cell2.innerHTML = item.name;
                    cells.push(cell2);
                console.log(cells);
                let cell3 = document.createElement('th');
                    cell3.innerHTML = item.lName;
                    cells.push(cell3);
                console.log(cells);
                    editButton.className = 'crud__DeleteEditButton form-control'; //настройка кнопки изменения
                    editButton.setAttribute('data-toggle', 'modal');
                    editButton.setAttribute('data-target', '#editModal');
                    editButton.innerHTML = 'Изменить';
                let cell4 = document.createElement('th');
                    cell4.appendChild(editButton);
                    cells.push(cell4);
                console.log(cells);
                    deleteButton.className = 'crud__DeleteEditButton form-control'; //настройка кнопки удаления
                    //deleteButton.addEventListener('click',this.deleteUser,false)
                    deleteButton.innerHTML = 'Удалить';
                let cell5 = document.createElement('th');
                    cell5.appendChild(deleteButton);
                    cells.push(cell5);
                console.log(cells);
                    for (let tempCell of cells){
                         console.log('appending');
                         row.appendChild(tempCell);
                     }
                    row.addEventListener('click',this.getTarget,false)
                    tBody.append(row); //добавить строку в таблицу
            }
            Table.append(tBody); // добавить тело к таблице
            console.log('drawing done');
    }
    ngOnInit ():void {
        this.drawTable();
    }
}

(sorry for russian tho)

J. Doe
  • 75
  • 1
  • 1
  • 10

1 Answers1

2

Change

row.addEventListener('click',this.getTarget,false)

to

row.addEventListener('click',this.getTarget.bind(this),false)

or

row.addEventListener('click', () => this.getTarget(),false)

your this is not refering to your component otherwise.

Suggested reading: How to access the correct `this` context inside a callback?

Community
  • 1
  • 1
eko
  • 39,722
  • 10
  • 72
  • 98
  • 1
    yup this worked, thank you – J. Doe May 18 '17 at 08:01
  • *"Suggested reading: How to access the correct `this` context inside a callback?"* If a question is a duplicate, vote to close as duplicate, rather than answering it. As a gold badge holder in the JavaScript tag, you have a dupehammer, I believe... – T.J. Crowder May 18 '17 at 08:20
  • @T.J.Crowder I couldn't agree more sir but when I mark these type of questions I tend to get comments like "how is that link related to my question?" and that's the politest type of comments. So now I quickly answer the question and give the link to the source of the problem. If the OP reads it, it's to their benefit if not, case is already closed. Another case is that I flag the question and the question gets answered with my type of answer and gets accepted like this. When I get the gold badge I'll lock these type of questions if I come across them but untill then this seems better :/ – eko May 18 '17 at 08:28
  • 1
    No, answering duplicates is actively harmful to SO. Instead: Vote to close, and optionally post a *comment* if you think it's useful pointing out how the linked question applies to their answer. Yes, people complain when we try to point them to canonical questions. That's not a reason not to do it. – T.J. Crowder May 18 '17 at 08:32