【问题标题】:Angular 2 mentions : How to update an array bind to a directive after an api callAngular 2 提到:如何在 api 调用后更新绑定到指令的数组
【发布时间】:2018-03-05 15:51:01
【问题描述】:

我正在使用这个包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


【解决方案1】:

也许你应该这样尝试一下

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

或设置其他在您获取数据后为真的标志。

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

【讨论】:

    【解决方案2】:

    添加项目后,您需要更新数组的整个引用。完成推送新数据后,您必须执行以下操作:

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

    如果模型中的任何东西发生了变化但没有反映视图,这意味着什么,你可能需要通知 Angular 来检测这些变化(检测本地更改)并更新视图。

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

    【讨论】:

      【解决方案3】:

      [提及]="users.length>0 ? users : []"

      使用此条件进行提及。只有加载 users 数组时才会设置值。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-27
        • 2021-12-17
        • 2016-10-01
        • 2015-04-15
        相关资源
        最近更新 更多