When I run this program, initially I get the output as false
, 5
, 500
as I have initialized them in the child component like that, but when I try to click on update button, I am not able to revert to the previous values. I am expecting the output to be true
, 10
, 1000
, but I am getting it as false
, 5
, 1000
. Only the number which was different got changed.
How can I solve this issue so that I can get the values whatever I set in the parent component?
Link to stackblitz.
app-component.html
<span (click)="clickme()">Update data</span>
app-component.ts
export class AppComponent {
public parentBool: boolean;
public parentNum: number;
public p2: number;
public ngOnInit(): void {
this.parentBool = true;
this.parentNum = 10;
this.p2 = 100;
}
public clickme(): void {
this.parentBool = true;
this.parentNum = 10;
this.p2 = 1000;
}
}
hello.component.ts
@Component({
selector: 'hello-comp',
template: `
<div>
Boolean value is - {{boolChild}} <br/>
Number value is - {{numChild}} <br />
Second number is - {{numChild2}}
</div>
`,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class MyComponent {
@Input() boolChild: boolean;
@Input() numChild: number;
@Input() numChild2: number;
public ngOnInit(): void {
this.boolChild = false;
this.numChild = 5;
this.numChild2 = 500;
}
constructor(private _cd: ChangeDetectorRef){}
public ngOnChanges(changes: {}): void {
// this._cd.detectChanges();
console.log(changes);
}
}
Input bindings occur right before ngOnInit, you’re overriding the values in ngOnInit.
Put your defaults in the declaration:
@Input() numChild: number = 5;
Like that
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With