首页 文章

如何从父组件调用html事件方法到子组件

提问于
浏览
0

我正在关注 parent 组件 .

JS

import { Component, OnInit } from '@angular/core';
import { TaskService } from '../task.service';
import { ViewChild } from '@angular/core/src/metadata/di';
import { CreateNewTaskComponent } from '../create-new-task/create-new-task.component';

@Component({
selector: 'task-list',
templateUrl: './task-list.component.html',
styleUrls: ['./task-list.component.css']
})
export class TaskListComponent implements OnInit {
    tasks = [{}];

    constructor(public taskService: TaskService) {
      debugger;
      this.tasks = taskService.tasks;
    }

    ngOnInit() {
    }

    completeTask(task){
      task.completed = true;
    }
}

HTML

<h3>Completed Task List</h3>
    <table>
        <tr>
            <th>Task Title</th>
            <th>Task Status</th>
            <th>Actions</th>
        </tr>
        <tr *ngIf="tasks.length == 0">
            <td colspan="3">No Record To Display</td>
        </tr>
        <tr *ngFor="let task of tasks">
            <td>{{task.title}}</td>
            <td>{{task.completed ? 'Completed' : 'Pending'}}</td>
            <td>
            <button *ngIf="!task.completed" (click)="completeTask(task)">Complete</button>
            <button (click)="**editTask**(task)">Edit</button>
            </td>
        </tr>
    </table>
    <create-new-task></create-new-task>

上面是从parent到child组件的editTask()事件绑定调用 .

以下是 child 组件

JS

import { Component, OnInit } from '@angular/core';
import { TaskService } from '../task.service';

@Component({
  selector: 'create-new-task',
  templateUrl: './create-new-task.component.html',
  styleUrls: ['./create-new-task.component.css']
})
export class CreateNewTaskComponent implements OnInit {
  task;
  constructor(public taskService: TaskService) {
    this.task = {id:0, title: '', completed: false};
  }

  ngOnInit() {
  }

  createTask(){
    debugger;
    this.task.completed = false;
    this.task.id = this.taskService.tasks.length;
    this.taskService.tasks.push(this.task);
    this.task = {id:0, title: '', completed: false};
  }

  editTask(task){
    alert("Called");
  }


}

HTML

<div class="createTask">
        <h3>Create New Task</h3>
        <hr/>
    <input type="text" [(ngModel)]="task.title"/>
    <button (click)="createTask()">Save</button>
    </div>

现在,当我点击父组件编辑按钮时,我收到以下错误:

错误TypeError:对象不支持属性或方法'editTask'

请帮忙!

1 回答

  • 0

    在您的父组件中添加以下行:

    @ViewChild(CreateNewTaskComponent) comp: CreateNewTaskComponent;
    

    然后在你的HTML中,你可以做到

    (click)="comp.editTask(task)"
    

相关问题