Angular 2 Child Reference To Variable Into Parent
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. @Compon
Solution 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>
`,
})
exportclassApp {
name:string;
constructor() {
this.name = 'Angular2'
}
}
@Component({
selector: 'child',
template: `
<div>
<h2>{{name}}</h2>
<button (click) = "rename()" > Rename Parent </button>
</div>
`,
})
exportclassChild {
@Input() name:string;
@Output() nameChanged: EventEmitter<string> = newEventEmitter<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.
Solution 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
Post a Comment for "Angular 2 Child Reference To Variable Into Parent"