angular 2 child reference to variable into parent

2019-09-06 09:41发布

问题:

How to change the value of a variable or use a method in a parent component from a child component without using input and output

I try something like this but not working.

@Component({
  selector: 'child',
  template: `
    <div>
      <h2>{{name}}</h2>
      <button (click) = "rename()" > Rename Parent </button>
    </div>
  `,
})
export class Child {
  name:string;
  constructor() {
    this.name = 'child'
  }

  rename() {
    App.name = 'Rename';
  }

}

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
    </div>
    <child> </child>
  `,
})
export class App {
  name:string;
  constructor() {
    this.name = 'Angular2'
  }
}

example here

plunker example

回答1:

Input and Output are just made for this. It is, according to the Angular2 Documentation, made for communication between parent and child components.

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
    </div>
    <child [name]="this.name" (nameChanged)="this.name = $event"> </child>
  `,
})
export class App {
  name:string;
  constructor() {
    this.name = 'Angular2'
  }
}

@Component({
  selector: 'child',
  template: `
    <div>
      <h2>{{name}}</h2>
      <button (click) = "rename()" > Rename Parent </button>
    </div>
  `,
})
export class Child {

@Input() name:string;
@Output() nameChanged: EventEmitter<string> = new EventEmitter<string>();

  constructor() {
  }

  rename() {
    this.nameChanged.emit('Renamed');
  }

}

Alternatively you could inject a service into both parent and child component, which has some values that both parent and child can access and modify. But make sure to add that service to either only the parent component or only the AppModule, otherwise you would get 2 instances of your service.



回答2:

That is @Output and @Input in Angular 2. Docs: https://angular.io/docs/ts/latest/cookbook/component-communication.html

  • Another way that is Observable, Subject you can also inject data from a child component to root component or from a component to another component : See this video: https://www.youtube.com/watch?v=U2qJxfi7370&list=PLFaW_8zE4amNEdKZOJD3P_GeV3Hgva7RD&index=10