首页 > 解决方案 > @Input decorator not working when value changes

问题描述

I have a weird problem. I use @Input to pass data from parents to child component. The data will be updated through subscribe, but upon changing the value it doesn't get pass to the child component.

Parent component

<app-family-tab [pheno]="pheno" [samples]="ids"></app-family-tab>

public ids: string[] = [];
this.subscriptions.push(this.sampleSearch.results.subscribe(s => {
    this.ids = s.samples;
    this.cd.detectChanges();
}));

Child component

import { Component, ChangeDetectorRef, OnDestroy, Input, Output, EventEmitter, OnInit, AfterViewInit, ChangeDetectionStrategy } from '@angular/core';

@Component({
  selector: 'app-family-tab',
  templateUrl: './family-tab.component.html',
  styleUrls: ['./family-tab.component.css']
})
export class FamilyTabComponent implements AfterViewInit {
  @Input() pheno: any;
  @Input() samples: string[];
  constructor() { }

  ngAfterViewInit(){
    console.log(this.samples);
  }

}

samples doesn't get updated on child component

标签: angular

解决方案


ngAfterViewInit()只调用一次(参见文档)。您可能希望监控每次更改时运行的Input属性。ngOnChanges()Input

你可以这样做,使用SimpleChanges参数:

ngOnChanges(changes: SimpleChanges) {
  console.log(changes);
}

console.log应该返回一个以您的属性名称作为键以及以前和当前值的对象:

{
  samples: { 
    currentValue: {...}, 
    firstChange: true|false, 
    previousValue: {...} 
  }
}

推荐阅读