Angular 2提到:如何在api调用后更新数组绑定到指令

问题描述 投票:0回答:3

我正在使用这个包https://www.npmjs.com/package/angular2-mentions。所以我的代码是这样的:

.ts file :
  ngOnInit():void {
    this.items.push("temp Name")
    let __this = this
    this._userService.getAll(1).subscribe(res => {
      res.users.forEach(function (a,b) {
        __this.items.push(a)
      })
      console.log(__this.items)
    })
  }

.html文件:

<input type="text" [mention]="items"  >

数组已更新,并且具有来自api的数据,但指令[提及]绑定到旧数组包含在开始时静态初始化的值!

angular angular2-directives mention
3个回答
0
投票

也许你应该尝试这样的

<input *ngIf="items.length > 0" type="text" [mention]="items">

或者设置获取数据后其他标志。

它可以工作,因为它会在您获取数据后呈现输入。


0
投票

添加项目后,需要更新数组的整个引用。在完成数组新数据的推送后,你必须做类似的事情:

this.__items = this.__items.slice();
this.ref.markForCheck();

如果存在模型中的任何内容发生更改但未反映视图的情况,则可能需要通知Angular检测这些更改(检测本地更改)并更新视图。

你还可以做的是DoCheck接口的实现。默认更改检测算法通过在更改检测运行之间通过引用比较绑定属性值来查找差异。除默认算法外,还会调用ngDoCheck来检查指令中的更改。


0
投票

[提及] =“users.length> 0?用户:[]”

使用这个条件提。仅在加载用户数组时才设置该值。

© www.soinside.com 2019 - 2024. All rights reserved.