licer93
licer93

Reputation: 351

Bad practice to modify data by importing parent component?

Let's say I have my TenantsComponent which has data like an array of objects called tenant (what a tenant is, is not important).

If for example I want to modify this data in another component called let's say TenantEditComponent, is it bad to import the component TenantsComponent in the TenantEditComponent and modify data like this ?

import TenantsComponent from ....;

@Component({
  selector: 'tenant-edit',
  templateUrl: './tenant.edit.html',
  styleUrls: ['./tenant.edit.css']
})

export class TenantEditComponent {

   constructor(public TenantsComponent: TenantsComponent) {

   }

   .
   .
   .

   aFunctionToModifyDataOfTenantsComponent() {
    this.TenantsComponent.tenants[0] = ...;
   }

Upvotes: 0

Views: 121

Answers (1)

Dane Brouwer
Dane Brouwer

Reputation: 2972

It's generally bad practice to import a component and change it's data explicitly.

There are two better options that I can think of.

Option One: Pass the data down into a child component via Input() and mutate it in the child. see Angular Component Interaction

Option Two: Use a service as your source of truth, and then you can pass the data into any other component to either view or mutate. Since you'll have a single source of truth, the changes would be reflected throughout the data's use. see Example of State Management

Upvotes: 1

Related Questions