我是ngOnchanges的新手,面对下面的问题。
我的父组件正在ngOnChanges上设置recom值,并将相同的值发送给子组件。子程序接收的输入与ngOnChanges中的输入相同。根据totalVal>0这样的条件,我将inputField设置为true,最初设置为false。如果inputField是真的,我会以反应性的形式显示一些组件。但是,当我的下面的结构执行model2Form()时,它仍然将inputField作为false。我不能发布实际的代码,所以只是按照我的项目创建了一个结构,如下所示。
请建议我如何解决这个问题。
// parent component
ngOnchanges(){
this.recom = [{
totalVal: 5000,
monthlydata: true
}]
}
//child component
@Input()
private recom: any;
inputField: boolean = false;
ngOnChanges(){
this.setValue();
this.loadFuture();
}
setValue(){
if(this.recom.totalVal > 0){
this.inputField = true;
}
}
loadFuture(){
}
model2Form(){
//getting input field as false even if i set it as true in setValue()
if(inputField){
this.heroForm.setControl('secretLairs', addressFormArray);
}
}
<!-- parent component>
<parent-comp [recom]="recom"></parent-comp>
<!-- child component -->
<div [FormControlName]="secretLairs"> </div>发布于 2017-12-07 14:19:56
问题是,您正在试图监视Array上的更改。数组和对象在ngOnChanges中不能很好地工作,因为它们是通过引用而不是通过值传递的。字符串和整数在这里工作得很好,因为它很容易判断何时改变了值。由于Javascript通过引用传递对象和数组,只有当引用发生变化时,角才会触发变化检测。
解决这个问题的三种方法是:
@Inputs(),它监视字符串或数字之类的值。发布于 2017-12-07 15:00:12
只有在对组件的输入属性进行任何更改时,才会发生更改事件ngOnchange。因此,在您的示例中,parentcomponent没有输入属性,因此ngOnchange不会为您触发。
我为您创建了正在工作的代码--在下面的代码中,我在我的appcomponent.ts中使用了父组件,当我加载时,ngOnchange不工作,但是子ngOnchange工作,它的输入属性被更改。
因此,我在textbox控件的OnChange事件中更改了子属性,当我在textbox控件中更改值时,子控件ngOnchange被触发,更新的值出现。
如果您将输入值传递给父控件并对其进行更改,则父控件和子控件将工作。
父组件
import { Component } from '@angular/core';
import { OnChanges, SimpleChanges, OnInit } from '@angular/core';
@Component({
selector: 'parentcomp',
template: `
this needs to be wok
<h3>Countdown to Liftoff (via local variable)</h3>
<input type="text" [ngModel] = "display" (ngModelChange)="onChange($event)"/>
{{display}}
<Childcomp [recom] = "recom"> </Childcomp>
`
})
export class ParentComponent implements OnChanges, OnInit {
ngOnInit(): void {
this.recom = [{
totalVal: 5000,
monthlydata: false
}];
}
display: string;
recom: any;
constructor() {
this.display = "test";
}
onChange()
{
this.recom = [{
totalVal: 5000,
monthlydata: true
}];
}
//this will not trigger
ngOnChanges(changes: SimpleChanges): void {
debugger;
this.recom = [{
totalVal: 5000,
monthlydata: true
}];
}
}子组件
import { Component } from '@angular/core';
import { OnChanges, SimpleChanges, Input } from '@angular/core';
@Component({
selector: 'Childcomp',
template: `
<h3>Child component</h3>
`
})
export class Childcomponent implements OnChanges {
@Input()
private recom: any;
constructor() {
}
ngOnChanges(changes: SimpleChanges): void {
debugger;
for (let propName in changes) {
let chng = changes[propName];
let cur:any = chng.currentValue;
let prev:any = chng.previousValue;
alert(`${propName}: currentValue = ${cur[0].monthlydata}, previousValue = ${prev[0].monthlydata}`);
}
}
}https://stackoverflow.com/questions/47696848
复制相似问题