Accessing a property in a parent Component

后端 未结 6 697
春和景丽
春和景丽 2020-11-29 23:41

I have a property in a top level Component that is used data from a HTTP source like so (this is in a file called app.ts):

import {UserData} fro         


        
6条回答
  •  执念已碎
    2020-11-30 00:22

    I had the same problem but I solved it differently. I don't know if it's a good way of doing it, but it works great for what I need.

    I used @Inject on the constructor of the child component, like this:

    import { Component, OnInit, Inject } from '@angular/core';
    import { ParentComponent } from '../views/parent/parent.component';
    
    export class ChildComponent{
        constructor(@Inject(ParentComponent) private parent: ParentComponent){
    
        }
    
        someMethod(){
            this.parent.aPublicProperty = 2;
        }
    }
    

    This worked for me, you only need to declare the method or property you want to call as public.

    In my case, the AppComponent handles the routing, and I'm using badges in the menu items to alert the user that new unread messages are available. So everytime a user reads a message, I want that counter to refresh, so I call the refresh method so that the number at the menu nav gets updated with the new value. This is probably not the best way but I like it for its simplicity.

提交回复
热议问题