How can i access the values from parent component

2020-03-26 07:15发布

问题:

I have two components one parent and a child i want to access a variable in parent component from child using DI but i am not getting that.i have made a plunker demo http://plnkr.co/edit/fcfweLJAmadKVWKXF25l?p=preview ... I tried to access the value of variable from child and got corrrectly but not from parent to child.This is how i am accessing variable in child component

@Component({
  selector: 'child',
  providers:[AppComponent]
  template: '<h1>My second Angular 2 App</h1>'
})
class NameComponent {
  name:string;
  constructor(AppComponent: AppComponent) {
    this.name = AppComponent.getName();
    console.log(this.name);
  }
}

I want to know is it possible to access variable from parent using DI? some body please tell me how to get the values

回答1:

Yes, it's possible but you need to leverage forwardRef as described below because you can't use hoisting:

@Inject(forwardRef(() => AppComponent)) app:AppComponent

Here is the complete sample:

@Component({
  selector: 'child',
  providers:[AppComponent]
  template: '<h1>My second Angular 2 App</h1>'
})
class NameComponent {
  name:string;
  constructor(@Inject(forwardRef(() => AppComponent)) appComponent: AppComponent) {
    this.name = appComponent.getName();
    console.log(this.name);
  }
}

@Component({
})
class AppComponent {
}

Here is the updated plunkr: http://plnkr.co/edit/brmQ01wFWrWvXmxpJpCc?p=preview.

This article written by Christoph Burgdorf could also help you:

  • http://blog.thoughtram.io/angular/2015/09/03/forward-references-in-angular-2.html

We should also be careful of cyclic dependency if classes are defined into separate modules / files: the parent component imports the child one and the child one imports the parent one...



回答2:

You would have to inject a service in parent component (in providers entry), set the value you want to use and than use it in child component.

@Component({
  selector: 'app',
  providers:[YourService]
  template: '<childCmp></childCmp>'
})
class AppComponent {
  constructor(private yourService: YourService) {
    this.yourService.setData(data);
  }
}

@Component({
  selector: 'childCmp',
  template: '{{yourService.getData()}}'
})
class ChildCmp {
  constructor(private yourService: YourService) {
    this.yourService.setData(value);
  }
}


标签: angular