从一个类中的另一个方法调用方法(this.function不起作用)

时间:2019-08-12 08:25:07

标签: angular typescript

我正在Angular中开发我的第一个应用程序,即使在StackOverflow和Internet页面中多次提到它,我仍然遇到问题,但是在我看来,它不起作用。这是我的简短代码:

export class PropertiesComponent implements OnInit, AfterViewInit {

  constructor(private renderer: Renderer2) {
    this.todoForm = document.getElementById('todo-form');
    this.session1 = sessionStorage.getItem('name');
    this.addInput = document.getElementById('add-input');
    this.todoList = document.getElementById('todo-list');
    this.todoItems = document.querySelectorAll('.todo-item');
    this.oldAddress = '';  
  };

  ngOnInit() {
    document.addEventListener('DOMContentLoaded', function () {
      this.todoForm.addEventListener('submit', this.addTodoItem);
      this.todoItems.forEach(item => this.bindEvents(item));
    });
    this.addresses = this.fetchUserAddreses();
  };
  createElement(tag, properties, ...children) {
    //code here
    return element;
  };

  createTodoItem(title) {
    //code here
    return listItem;
  };

  bindEvents(todoItem) {
    const editButton = todoItem.querySelector('.edit');
    const deleteButton = todoItem.querySelector('.delete');
    editButton.addEventListener('click', this.editTodoItem);
    deleteButton.addEventListener('click', this.deleteTodoItem);
  };

  addTodoItem(event) {
    //code here
  };

  editUserAddress(oldAddress: any, newAddress: any) {
    //code here
  };

  editTodoItem() {
    //code here
    const title = listItem.querySelector('.title');
    ** this.editUserAddress(this.oldAddress, title.innerText); ** //!! error this.editUserAddress(); is not a function
  };

  fetchUserAddreses() {
    //code here
  }
  addUserAddress(event: any) {
    //code here
  }
}

问题在这一行 this.editUserAddress(this.oldAddress, title.innerText); //!! error this.editUserAddress is not a function 如果需要,我可以显示完整的代码。

1 个答案:

答案 0 :(得分:0)

尝试使用箭头功能,它将功能绑定到当前实例

editTodoItem = () => {
    const title = listItem.querySelector('.title');
    this.editUserAddress(this.oldAddress, title.innerText);
}