尝试使用viewChild()从模块中的一个组件获取值到app.component.ts

问题描述 投票:0回答:3

我试图使用app.component.ts中的视图子项将模块的组件中存在的属性(bookmarkedCount)值提供给app组件。但是我在读取app组件中的属性值时出错是未定义的。为什么会这样?

错误TypeError:无法在AppComponent.push读取属性'bookmarkedCount'。/ src / app / app.component.ts.AppComponent.ngAfterViewInit(app.component.ts:36)

app.component.ts

@ViewChild(ContainerComponent) private containerComponent:ContainerComponent;

ngAfterViewInit(): void {
    this.count = this.containerComponent.bookmarkedCount;  //getting error here reading the value of bookmarkedCount
}
angular angular-components
3个回答
0
投票

试试这样 -

export class AppComponent  {
    bookmarkedCount: any;
    constructor(private containerComponentComponent: ContainerComponentComponent){
        this.bookmarkedCount = this.containerComponentComponent.bookmarkedCount;
   }
}

details here


0
投票

我想你在这里以正确的方式做到了

但有时在孩子被渲染之前会调用ngAfterViewInit()。我们通常使用ngOnInit()进行这种绑定。

所以尝试这样..

@ViewChild(ContainerComponent) private containerComponent:ContainerComponent;

ngOnInit() {
    this.count = this.containerComponent.bookmarkedCount;  
}

我希望这能解决你的问题:)


0
投票

没有找到任何更容易的替代解决方案。因此,我创建了一个共享服务,以获取app组件中的bookmarkedCount的值,并在服务中的更改中更新它。每当我点击添加/删除书签时,我都在调用changeCount方法

 //for bookmark count 
  private count:number;

  private messageSource = new BehaviorSubject(this.count);
  currentCount = this.messageSource.asObservable();

  changeCount(count: number) {
    if(count!=undefined)
    this.messageSource.next(count);
  }

在app.component.ts中 - >

  updateCount(){
    this.dataService.currentCount.subscribe(res => {
      this.count = res;
    });
    return true;
  }
© www.soinside.com 2019 - 2024. All rights reserved.