How can I access values ​​from a parent component in angular2 using dependency injection?

I have two components: one parent and child, I want to access the variable in the parent component from the child using DI, but I do not get this. I did a plunker demo http://plnkr.co/edit/fcfweLJAmadKVWKXF25l?p=preview ... I tried to access the value of a variable from a child and got it correctly, but not from parent to child. This is how I access a variable in a 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 if it is possible to access a variable from a parent using DI? some bodies please tell me how to get the values

+2
source share
2

, , forwardRef, , :

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

:

@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 {
}

plunkr: http://plnkr.co/edit/brmQ01wFWrWvXmxpJpCc?p=preview.

, , :

, /: , - ...

+12

( ), , , .

@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);
  }
}
0

Source: https://habr.com/ru/post/1627029/


All Articles