Home > Back-end >  Angular 10/Typescript: What is the difference between how the same property of an object is being as
Angular 10/Typescript: What is the difference between how the same property of an object is being as

Time:02-25

I have an object Person being passed on from a parent component as shown below. The name is initialized to an empty string when declaring the property before ngOnInit(). The property is used to set a boolean in another component. Even though the parent component has a value of name = John in the parent component, scenario 1 wipes that value out to an empty string thus affecting the boolean. Scenario 2 does not alter the value of name = John. What is the difference between the two assignments in scenario 1 and 2? and why is scenario 1 wiping out the original value in the parent component?

export interface IPerson {
 name?: string;
}

// In a child component:
@Input() person: IPerson = { name: '' }

// scenario 1:
ngOnInit(): void {

  this.person.name = '';

}

// scenario 2:
ngOnInit(): void {
this.person = { name: '' }

}

CodePudding user response:

I think this becomes more clear if you use a distinct value instead of an empty string. Say we have the same setup:

export interface IPerson {
    name?: string
}

@Component({ 
  selector: 'app-parent', 
  template: `
    <p>Parent value: {{person.name}}</p>
    <app-child [person]="person"></app-child>`
})
export class ParentComponent {
  person: IPerson = { name: 'John' };
}

@Component({
  selector: 'app-child',
  template: `<p>Child value: {{person.name}}</p>`
})
export class ChildComponent implements OnInit {
  @Input() person: IPerson = { name: '' };

  ngOnInit() {
    // Scenario 1:
    this.person.name = 'Felicity';
    // Scenario 2:
    this.person = { name: 'Norah' };
  }
}

When you render the parent component, you'll see something similar to this:

Parent value: Felicity
Child value: Norah

This is because in scenario 1, we have changed the name field on the parent's object. It was passed "by reference" if you will, so modifications on the field have changed what the parent knows.

Scenario 2 has forgotten about the object from the parent and replaced it with a new object that only the child knows about. Hence we see two different names; one in the parent and one in the child.

Play around with it using this StackBlitz.


In your case, scenario 1 overwrites "John" because you're changing the actual object passed from the parent. Scenario 2 does not overwrite "John" because you're working with a new object, not the one passed from the parent.

  • Related