My angular component is like below:
我的角度分量如下所示:
@Component({
selector: 'request-Component'
templateUrls: './request.component.html'
styleUrls: ['./request.component.scss']
})
export class ChildComponent implements OnInit, OnDestroy, OnChanges {
@Input() filters: FilterMetadata;
constructor(private service: RequestService){}
ngOnInit(): void {this.service.GetRequests(this.filters);}
ngOnChanges(changes: SimpleChanges): void {
console.info('ngOnChanges: ', changes['filters']);
this.service.GetRequests(this.filters);
}
}
Below is how I am injecting this component in the caller:
下面是我如何将该组件注入调用方:
<request-Component [filters]='filtersData'></request-Component>
Below is the FilterMetadata interface:
下面是FilterMetadata接口:
export default interface FilterMetadata{
country: string;
state: string;
city: string;
}
Below is how the input to child is set in the caller component:
下面是调用者组件中如何设置对子对象的输入:
setFiltersData() {
this.FiltersData = {
country: 'testCountry',
state: 'testState',
city: 'testCity'
}
}
I am able to solve this by explicitly implement a getter and setter on the Input in the child component but I want to know why ngOnChanges is not detecting the change.
我可以通过对子组件中的输入显式实现一个getter和setter来解决这个问题,但我想知道为什么ngOnChanges没有检测到更改。
更多回答
it should trigger. moreover you should be able to call GetRequests only in ngOnChanges, because it would trigger at sart as wel
它应该会触发。此外,您应该只能在ngOnChanges中调用GetRequest,因为它将在Sart时触发
Can you double check that the code pasted is copied correctly? You have a variable FiltersData
(uppercase F) being updated instead of filtersData
(lowercase f) which would mean your data is never passed to the child component
你能再检查一下粘贴的代码是否被正确复制吗?您将更新变量FiltersData(大写F),而不是FiltersData(小写f),这意味着您的数据永远不会传递给子组件
@Andrei - onInit supports the call as well as it can be null or preset. But anyway, the real issue is it's not working
@Andrei-onInit支持调用,可以为空,也可以为预设。但不管怎样,真正的问题是它不起作用
@nate-kumar - sorry for the typo, it is filtersData. But that's not the issue here.
@Nate-Kumar-抱歉打字错误,它是filtersData。但这不是这里的问题所在。
优秀答案推荐
The ngOnChanges
method is triggered exclusively when there is a modification in the Input property that originates from a template binding. However, if you manually assign a value to the property like object = {key: newValue}
, this occurs outside the change detection cycle, and you must inform Angular explicitly that a change has been made.
当源自模板绑定的输入属性发生修改时,将以独占方式触发ngOnChanges方法。但是,如果手动为属性赋值,如Object={key:newValue},则这会在更改检测周期之外发生,并且您必须明确通知ANGLE已进行更改。
Besides getter/setter approach you can use:
除了getter/setter方法之外,您还可以使用:
updateNewData(newValue) {
this.object= newValue;
this.changeDetectorRef.detectChanges();
}
Luckily, ngOnChanges
will be invoked.
幸运的是,将调用ngOnChanges。
更多回答
我是一名优秀的程序员,十分优秀!