我有以下父组件。
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>
上面是从父组件到子组件的事件绑定调用editTask()。
以下是子组件
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:Object不支持属性或方法'editTask'
请帮忙!
答案 0 :(得分:0)
在您的父组件中添加以下行:
@ViewChild(CreateNewTaskComponent) comp: CreateNewTaskComponent;
然后在你的HTML中你可以做
(click)="comp.editTask(task)"