@ViewChild 值在父级中不可用?

@ViewChild value is not available in parent?

组件是:

export class DictionaryComponent implements OnInit, AfterViewInit {
  @ViewChild(ViewModeComponent)
  primarySampleComponent: ViewModeComponent;

   ngAfterViewInit() {
      console.log('Values on ngAfterViewInit():');
      console.log(this.primarySampleComponent.viewMode);

    }  

}

子项 组件是 ViewModeComponent:

export class ViewModeComponent {

  public viewMode: mode = 'inline';
  public constructor(
  ) {}

  public switchMode(mode: mode) {
    this.viewMode = mode;
  }
}

为什么在更改子组件中的值 this.viewMode 后,我没有在父组件 ngAfterViewInit() {} 中收到它的值?

Console.log什么都没说。

Angular版本为8

使用 Observables

服役

private viewMode = new BehaviorSubject(false); // create observable variable
checkMode = this.viewMode.asObservable();

changeMode(falg) {
    this.viewMode.next(falg);
}

在子组件中:

this.viewMode // local variable of Component

public switchMode(mode: mode) {
    this.viewMode = mode;
    this.service.changeMode(mode); // setting value to observable variable
}

在父组件中:

this.viewMode // local variable of Component
this.service.checkMode.subscribe(response => this.viewMode = response); // get the value

您可以使用 EventEmitter 实现相同的效果。只需在子组件中创建一个 EventEmitter 并将事件传递给父组件..!

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

您可以在 stackblitz 中查看实时示例 here..!

您可以使用 EventEmitter 从您的子组件发出值

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
}