我将一个函数作为参数从父组件传递到子组件。当点击事件发生时,父组件的功能被触发,但是父组件的所有属性都是未定义的。例如,
父组件
export class AppComponent implements OnInit {
constructor( private notificationService: NotificationService ) {}
unreadNotification(): Observable<any> {
// here this.notificationService is undefined
console.log( this.notificationService );
}
}
父 html
<notification-menu [unread]= "unreadNotification"></notification-menu>
子组件
export class NotificationMenuComponent implements OnInit {
@Input() updateUnread: Function;
}
子 html
<button type="button" class="icon-button" (click)="updateUnread()">
</button>
现在当我点击通知按钮时,unreadNotification
被触发,但是 console.log
中的 this.notificationService
的值为 未定义
。
我该如何解决这个问题?
最佳答案
您应该使用 @Input()
将值从 parent 传递给 child 和 @Output()
将值从child 传递给parent。
子 HTML:
<button type="button" class="icon-button" (click)="update()">
</button>
子组件:
export class NotificationMenuComponent implements OnInit {
@Output() updateUnread = new EventEmitter<string>();
update() {
this.updateUnread.emit("I am working man!");
}
}
父 HTML:
<notification-menu (updateUnread)= "unreadNotification($event)"></notification-menu>
父组件:
export class AppComponent implements OnInit {
constructor( private notificationService: NotificationService ) {}
unreadNotification(dataFromChild: string) {
console.log(dataFromChild);
}
}
关于javascript - Angular - 无法获取父组件数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54967291/