我正在尝试通过将一个组件的引用传递给另一个组件,但收到“无法读取属性”错误来从一个组件调用另一个组件函数。这是代码
警报组件
import { Component, OnInit, Output } from '@angular/core';
@Component({
selector: 'app-alert',
templateUrl: './alert.component.html',
styleUrls: ['./alert.component.css']
})
export class AlertComponent implements OnInit {
AlertMessage:string;
constructor() {
}
showSuccessAlert(){
this.AlertMessage = "Data saved successfully.";
}
ngOnInit() {
}
}
警报组件html
<p>{{AlertMessage}}</p>
我正在从另一个组件调用showSuccessAlert
函数
组件
import { Component, OnInit, Input, HostListener } from '@angular/core';
import { QueueService } from 'src/services/queue.service';
import { ActivatedRoute } from "@angular/router";
import { NgForm } from '@angular/forms';
import { Queue } from 'src/models/queue';
import { error } from 'util';
import { AlertComponent } from '../alert/alert.component';
@Component({
selector: 'queue-edit',
templateUrl: './queue.edit.component.html'
})
export class QueueEditComponent implements OnInit{
@Input() alert:AlertComponent;
queue = new Queue();
constructor(private api: QueueService, private route: ActivatedRoute){
this.route.params.subscribe(params => this.params = params);
}
title = "Edit Support Queue";
ngOnInit() {
}
@HostListener('saveQueue')
saveQueue(queue){
this.alert.showSuccessAlert();
}
}
html
<app-alert></app-alert>
错误
ERROR TypeError: Cannot read property 'showSuccessAlert' of undefined
at QueueEditComponent.push../src/app/queue/queue.edit.component.ts.QueueEditComponent.saveQueue (queue.edit.component.ts:44)
at Object.eval [as handleEvent] (QueueEditComponent.html:25)
at handleEvent (core.js:19545)
at callWithDebugContext (core.js:20639)
at Object.debugHandleEvent [as handleEvent] (core.js:20342)
at dispatchEvent (core.js:16994)
at core.js:17441
at HTMLButtonElement.<anonymous> (platform-browser.js:993)
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:423)
at Object.onInvokeTask (core.js:14051)
答案 0 :(得分:3)
您应该使用@ViewChild
而不是@Input
。像这样:
import { ..., ViewChild } from '@angular/core';
...
import { AlertComponent } from '../alert/alert.component';
@Component({...})
export class QueueEditComponent implements OnInit{
@ViewChild(AlertComponent) alert:AlertComponent;
...
@HostListener('saveQueue')
saveQueue(queue){
this.alert.showSuccessAlert();
}
}
PS::只有在调用AlertComponent
之前,您才能访问QueueEditComponent
中的ngAfterViewInit
。因此,请确保您的saveQueue
在ngAfterViewInit
之后的某个时间被呼叫。