javascript - Angular - 无法获取父组件数据

标签 javascript angular typescript

我将一个函数作为参数从父组件传递到子组件。当点击事件发生时,父组件的功能被触发,但是父组件的所有属性都是未定义的。例如,

父组件

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/

相关文章:

javascript - 获取简短的 JavaScript CustomEvent polyfill 以在 TypeScript 中进行编译?

javascript - 单击"is"按钮时添加边框和背景颜色

javascript - 具有相同类的按钮在使用 JQuery Click 功能时出现问题

typescript - 提交表单后 Angular2 更新 View

angular - 如何在 Angular 2+ 中的元素上调用 scrollIntoView

testing - 在生产模式下隐藏 angular2 组件的最佳解决方案?

从类型参数进行 typescript 类型推断

javascript - 使用 Javascript 和 React 检测 DIV 中的滚动位置

javascript - 在 Google Maps Places API 中限制基于特定国家/地区的搜索

javascript - 使用“下一步”按钮生成并循环随机数数组