Reputation: 12005
Parent component is:
export class DictionaryComponent implements OnInit, AfterViewInit {
@ViewChild(ViewModeComponent)
primarySampleComponent: ViewModeComponent;
ngAfterViewInit() {
console.log('Values on ngAfterViewInit():');
console.log(this.primarySampleComponent.viewMode);
}
}
Children component is ViewModeComponent
:
export class ViewModeComponent {
public viewMode: mode = 'inline';
public constructor(
) {}
public switchMode(mode: mode) {
this.viewMode = mode;
}
}
Why after changing value this.viewMode in children component I don't receive it value in parent ngAfterViewInit() {}
?
Console.log says nothing.
Angular version is 8
Upvotes: 1
Views: 437
Reputation: 1415
You can use an EventEmitter
to emit values from your child components
parent.html
<ChildComponent (viewModeEvent)="handleViewModeChange($event)"></ChildCompoment>
child.component.ts
Import {..., Output, EventEmitter } from "@angular/core";
export class ViewModeComponent {
@Output() viewModeEvent = new EventEmitter<mode>();
public viewMode: mode = 'inline';
public constructor(
) {}
public switchMode(mode: mode) {
this.viewModeEvent.emit(mode)
}
}
parent.component.ts
handleViewModeChange(args: mode) {
// gets called everytime there is a viewMode change emitted from child
}
Upvotes: 1
Reputation: 3334
You can achieve the same using the EventEmitter
. Just make an EventEmitter in the child component and pass the event to the parent component..!
child.component.ts
export class ChildComponnent implements OnInit {
name: EventEmitter<string> = new EventEmitter<string>();
ngOnInit() {
setInterval(() => this.name.emit(new Date().toString()), 1000);
}
}
parent.component.ts
export class AppComponent implements OnInit {
@ViewChild('appChild', { static: true }) appChild: ChildComponnent;
ngOnInit() {
this.appChild.name.subscribe(console.log);
}
}
parent.component.html
<app-child #appChild></app-child>
{{(appChild.name | async) | json}}
You can see the live example in the stackblitz here..!
Upvotes: 0
Reputation: 1972
Use Observables
in Service
private viewMode = new BehaviorSubject(false); // create observable variable
checkMode = this.viewMode.asObservable();
changeMode(falg) {
this.viewMode.next(falg);
}
In Child Component :
this.viewMode // local variable of Component
public switchMode(mode: mode) {
this.viewMode = mode;
this.service.changeMode(mode); // setting value to observable variable
}
in Parent Component :
this.viewMode // local variable of Component
this.service.checkMode.subscribe(response => this.viewMode = response); // get the value
Upvotes: 1