打字稿变量似乎在设置后重置

时间:2018-12-29 23:53:44

标签: javascript typescript ionic-framework ionic3

我遇到了一个问题,到目前为止我还无法找到答案。我创建了ProfileData类的新实例,并通过setName()设置了profileName变量。我可以通过控制台的setName()和ngAfterViewInit()日志看到,profileName是在setName()期间设置的,但是已经被ngAfterViewInit()重新设置为“”。为什么会有这种情况发生?

AccountPage类

  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组件类

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);
  }
}

0 个答案:

没有答案