This question already has an answer here:
这个问题在这里已有答案:
- How to access the correct `this` inside a callback? 8 answers
如何在回调中访问正确的`this`? 8个答案
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:
嘿伙计们,我对Angular有些麻烦。我有一个对象数组和几个函数但其中一个数组是未定义的。所以有我的功能:
- getTarget()
- saveChanges()
- addUser()
- drawTable()
- ngOnInit() I'm trying to
console.log
my array in all these functions, and everything is ok butgetTarget()
function! It's just keeping to logundefined
into console while other functions' output is like(2) [Object, Object]
Why is the array unreachable or what's worng?
ngOnInit()我正在尝试在所有这些函数中调用我的数组,并且一切正常,但getTarget()函数!它只是保持将undefined记录到控制台,而其他函数的输出就像(2)[Object,Object]为什么数组无法访问或者是什么?
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)
(对不起俄罗斯人)
1 个解决方案
#1
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?
建议阅读:如何在回调中访问正确的`this`上下文?
#1
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?
建议阅读:如何在回调中访问正确的`this`上下文?