TS variable value seemingly resets

#1

I’m having a problem, one that I’ve not been able to find the answer for as of yet. I create a new instance of the ProfileData class and set the profileName variable via setName(). I can see via the console logs in setName() and ngAfterViewInit() that profileName is definitely set during setName(), but has already become " " again by ngAfterViewInit(). Is there a reason why this would be happening?

AccountPage Class

  export class AccountsPage {

  public profileList = new Array<ProfileDataComponent>();

  constructor(public navCtrl: NavController,
          public navParams: NavParams,
          private alertCtrl: AlertController) {
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad AccountsPage');
  }

  addProfile()
  {
    let alert = this.alertCtrl.create({
    title: 'Add Profile',
    inputs: [
      {
        name: 'name',
        placeholder: 'Profile Name'
      },
    ],
  buttons: [
  {
    text: 'Cancel',
    role: 'cancel',
    handler: data => {
      console.log('Cancel clicked');
    }
  },
  {
    text: 'Add',
    handler: data => {
      //Declare New Profile
      var newProfile = new ProfileDataComponent();
      newProfile.setName(data.name);

      //Create new list
      var newArray: ProfileDataComponent[] = new Array(this.profileList.length + 1);

      //Copy old list to new one
      for (var i = 0; i < this.profileList.length; i++)
      {
        newArray[i] = this.profileList[i];
      }
        newArray[newArray.length - 1] = newProfile;
        this.profileList = newArray;
    }
  }
]
  });
 alert.present();
  }
}

ProfileData Component Class

export class ProfileDataComponent {

  @ViewChild('profileName') nameElement;

  profileName: string = "";

  constructor()
  {

  }

  ngAfterViewInit()
  {
    this.nameElement.textContent = this.profileName;
    console.log('Set Name: ' + this.profileName);
  }

  setName(newName: string)
  {
    this.profileName = newName;
    console.log('Setting Name: ' + this.profileName);
  }
}
#2

Component lifecycle is always managed by Angular DI. Never attempt to instantiate components yourself. That is the cause of your problem.

#3

That makes sense. I’m still a bit unfamiliar with angular, is there a way to go about doing this without manually instantiating components?

#4

You generally want to use structural directives like ngFor to let Angular instantiate the necessary components, so you will only be modifying a backing array. See the Displaying a List section of the Tour of Heroes for an example.