angular - @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
解决方案
ngAfterViewInit()
只调用一次(参见文档)。您可能希望监控每次更改时运行的Input
属性。ngOnChanges()
Input
你可以这样做,使用SimpleChanges
参数:
ngOnChanges(changes: SimpleChanges) {
console.log(changes);
}
console.log
应该返回一个以您的属性名称作为键以及以前和当前值的对象:
{
samples: {
currentValue: {...},
firstChange: true|false,
previousValue: {...}
}
}
推荐阅读
- laravel - Laravel Sanctum SPA 验证不同的用户表
- azure - 如何从 Microsoft Azure 转出域?
- excel - 如何使用 VBA 更新循环内的范围
- java - 如何使用 Spring Kafka 保证 Kafka 主题配置
- vue.js - 在 Nuxt.js 中重新访问页面时如何不重新渲染组件?
- python - 错误:即使安装了请求,也没有名为请求的模块
- c++ - 如何在 C++ 中添加到数组文本文件?
- python - 根据数据框另一列值计数的数据框列到 2d numpy 数组
- list - 批处理将列出文件夹中的文件,问我是哪一个,当我选择它时会打开它
- python - Python:在 1 秒内运行 N 次函数