javascript - Angular 8 中通过引用调用组件数组属性

标签 javascript angular typescript copy angular8

我在 Angular 组件中有一个方法,它在方法中传递组件属性数组,但属性值没有改变:

private districtModel : LocationModel[] = [];

valueChange(apiService : ApiService,control : FormControl,url,targetModel: LocationModel[]) {
control.valueChanges.subscribe(newValue=>{

  if(control.value === ""){
    console.log("empty");
    console.log(this.stateTemp);
    this.stateModel = this.stateTemp;
  }
  else{
    this.stateModel = this.filterValues(newValue,this.stateModel);
  }

  if(this.stateModel.length===1){
    console.log(this.stateModel[0].id);
    apiService.GetLocationById<LocationModel[]>(url,this.stateModel[0].id)
    .subscribe(data=> {
      targetModel = data;
        //console.log(this.districtModel);
    });
  }
});
}

函数调用

this.valueChange(apiService,this.societyForm.controls['State'] as 
FormControl,"https://localhost:44355/Location/GetDistrict?StateId=",this.districtModel);

我想更改函数内 this.districtModel 的值,但它没有改变

最佳答案

这里

targetModel = data;

您将数据分配给局部变量targetModel,该变量不会更改this.districtModel。您可以做的是清除原始数组并为其分配新值:

targetModel.splice(0, targetModel.length, ...data);

这会从数组中从 0 开始删除 targetModel.length 项,并添加 data 中的所有项。

关于javascript - Angular 8 中通过引用调用组件数组属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58989205/

相关文章:

javascript - PhoneGap : Unable to change volume of html5 Audio object in ios

javascript - 如何使用 JavaScript 和“是/否”按钮来弹出年龄验证窗口?

javascript - 使用 Angular 5 调整 div 的高度和宽度(以百分比而非像素为单位)

javascript - Angular 2 : building svg icons with *ngIf adds nothing to DOM

json - 自动将 JSON 对象映射到 TypeScript 对象(Angular 2)

typescript - 从对象中获取可选的通用值

node.js - 类中的静态变量在 app.listen 的回调中未定义

javascript - 使文本适合 HTML5 Canvas?

javascript正则表达式单行

javascript - ReplaySubject(1) 和 AsyncSubject() 一样吗?