Home > Enterprise >  In Angular how to change a field member in a component or service automatically, when another depend
In Angular how to change a field member in a component or service automatically, when another depend

Time:05-19

import {Component} from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  fieldA = "";
  fieldB = `Hello ${this.fieldA}`;
  
  changeFieldA(){
    this.fieldA = "World";
  }
}

When the "changeFieldA" method is triggered, as I found at this moment, fieldB is still "Hello ", rather than "Hello World". I want to make fieldB "reactive" to fieldA, so that whenever fieldA's value changes, fieldB's value will instantly change at that moment.

I don't want to add an extra line of code in the "changeFieldA" method, like:

this.fieldB = `Hello ${this.fieldA}`;

so as to manually update the fieldB. I want to make the updating process totally automatic, because in the project I have a field which is a large nested object containing nested arrays, which makes the manual update like this very trivial.

CodePudding user response:

There are other ways of doing it, but the simplest way for this particular case would be to call a function within changeFieldA that resets the value of fieldB. For instance:

private syncFieldB() {
  this.fieldB = `Hello ${this.fieldA}`;
}
      
changeFieldA(){
  this.fieldA = "World";
  this.syncFieldB();
}

The complicated logic of setting fieldB can be contained in the syncFieldB function. If you need the value of fieldB to be set whenever the value of fieldA is modified (perhaps outside of the changeFieldA function), then maybe you could use get/set:

private _fieldA = "";

get fieldA() {
  return this._fieldA;
}

set fieldA(value) {
  this._fieldA = value;
  this.syncFieldB();
}

This method doesn't require you calling syncFieldB wherever you modify fieldA.

CodePudding user response:

You could change

fieldB = `Hello ${this.fieldA}`;

to

get fieldB() {
  return `Hello ${this.fieldA}`;
}

so that fieldB is a read-only computed property.

However, it's probably better to replace the fieldB property with a method, not a getter, because those confuse people, including you when you come back to this code months and months later. ;-)

  • Related