@ViewChild值在父级中不可用?

时间:2019-07-04 11:03:35

标签: angular angular8

父级组件是:

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什么也没说。

角度版本为8

3 个答案:

答案 0 :(得分:1)

使用可观察物

服务中

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

答案 1 :(得分:1)

您可以使用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
}

答案 2 :(得分:0)

您可以使用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}}

您可以在stack here中看到实时示例。.