Angular 即使值是硬编码的,也不会立即绑定数据

Angular does not bind data immediately even when value is hardcoded

我正在尝试将 A-Frame 集成到 Angular html 模板中,但我不完全了解 Angular 如何处理数据绑定。 A-Frame 库在 polyfills.ts.

中导入

给定模板:

<a-asset-item
  [attr.id]="'cityModel'"
  [attr.src]="'https://cdn.aframe.io/test-models/models/glTF-2.0/virtualcity/VC.gltf'"
  (error)="error($event)"
  (loaded)="assetItemLoaded($event)">
</a-asset-item>

Angular 将首先使用以下内容填充 dom:

<a-asset-item></a-asset-item>

None 个数据绑定 已绑定。 A-Frame 继续尝试从 <a-asset-item> 读取 idsrc,但因为它们尚未绑定(即使在本例中它们是硬编码的)它们将导致空错误。

Cannot read lastIdexOf null

如果我们忽略这个错误,接下来我们会看到 idsrc 都在 DOM 中分配,只是与 [=19= 时不同] 已创建。

<a-asset id="cityModel" src="https://cdn.aframe.io/test-models/models/glTF-2.0/virtualcity/VC.gltf">

这导致了一场比赛。 A-Frame 一出现在 DOM 上就急于从 a-asset-item 中读取。 Angular 急于将元素附加到 DOM 而不填充其所有属性。

有没有办法将元素及其属性同时附加到 DOM,同时保持数据绑定的好处?


补充更新:

我能够通过以下方式克服非立即绑定问题:

<a-asset-item
  id=""
  src=""
  [attr.id]="'cityModel'"
  [attr.src]="'https://cdn.aframe.io/test-models/models/glTF-2.0/virtualcity/VC.gltf'"
  (error)="error($event)"
  (loaded)="assetItemLoaded($event)">
</a-asset-item>

与元素相同的时间:

id=""
src=""

元素之后:

[attr.id]="'cityModel'"
[attr.src]="'https://cdn.aframe.io/test-models/models/glTF-2.0/virtualcity/VC.gltf'"

如果我直接修改A-Frame源代码,这可以是non-issue:

Angular:

<a-asset-item
  *ngFor="let model of assetItems; trackBy: trackAsset"
  [attr.id]="model?.id"
  [attr.src]="model?.asset?.file?.uri">
</a-asset-item>

aframe-v0.9.2.js:

registerElement('a-asset-item', {
  prototype: Object.create(ANode.prototype, {
    createdCallback: {
      value: function () {
        ...
      }
    },

    attachedCallback: {
      value: function () {
        var self = this;
        var src = this.getAttribute('src') || ''; // <--- Modified line
        ...
      }
    }
  })
});

这样,即使 Angular 最初在 data-binding 之前缺少 src,应用程序也不会出错。 Src 仍然可以毫无问题地更新和绑定。