【问题标题】:Set an array to attribute of an External Angular Component将数组设置为外部 Angular 组件的属性
【发布时间】:2019-03-24 14:02:40
【问题描述】:

我的问题如下:

我想从位于runtime 的远程服务器加载外部Angular 组件。感谢Manfred Steyer的博文,我设法做得很好

问题是我需要将一些data 对象传递给我在runtime 加载的组件。在来自Manfred Steyer 的帖子中,他这样做但不是为了对象。

我在一步一步做的事情:

首先,我创建一个单独的 Angular 项目,例如采用这样的数据对象:

内部RandomComponent.ts

Interface Random: {
   name: string;
   age: number;
}[]
@Input() data: Random;

内部RandomComponent.html

<div>
    <div *ngFor="let d of data">{{d.name}}</div>
</div>

接下来我构建这个组件并获得一个看起来像:random-component.bundle.js 的文件。我将此文件放在服务器上,并在需要时渲染它。

现在在主要的 Angular 项目中,我想加载这个文件并向他传递一个数据对象。如果关注Manfred Steyer 的博客,我会这样做:

// creation of element from bundle
const script = document.createElement('script');
script.src = 'assets/random-component.bundle.js';
document.body.appendChild(script);

// creation of new element based on selector from bundle
const data = [{name: 'Dave', age: 19}, {name: 'Charly', age: 23}];
const component = document.createElement('random-component');
component.setAttribute('data', data);

但是我不能设置这样的属性,有什么想法吗?

【问题讨论】:

    标签: angular typescript data-binding web-component


    【解决方案1】:

    检查random-component 组件中的@Input 名称。您正在尝试设置属性,以便组件中应该存在相同的名称。

    【讨论】:

    • 你好 Sunil,对不起,我忘了提到 @Input() 被称为数据!
    • 您是在正文中添加random-component 组件还是在创建后添加一些组件?
    • 是的,我做到了... const content = document.getElementById('content'); content.appendChild(component);
    • 为此需要执行多项检查。您可以做的是,删除所有内容并仅保留纯 html 内容并检查至少您是否可以在页面中看到该组件。接下来是设置属性。
    • 我已经可以在页面中看到组件了,所以那部分没问题,我只是不能传递数组或绑定数据:)
    【解决方案2】:

    对于那些感兴趣的人!

    我没有传递array,而是传递一个带有JSON.stringify(data) 的字符串化array,它返回一个string,然后我可以传递给属性:

    主要组件

      const component = document.createElement(identifier);
      component.setAttribute('data', JSON.stringify(data));
      const content = document.getElementById('content');
      content.appendChild(component);
    

    外部组件 - random.component.ts

      parseData(data: string) {
        return JSON.parse(data);
      }
    

    外部组件 - random.component.html

    <div>
        <div *ngFor="let d of parseData(data)">{{d.name}}</div>
    </div>
    

    有效!但是单向绑定存在一些问题

    【讨论】:

      猜你喜欢
      • 2020-05-05
      • 1970-01-01
      • 2019-05-05
      • 1970-01-01
      • 2021-10-29
      • 1970-01-01
      • 1970-01-01
      • 2016-07-04
      • 1970-01-01
      相关资源
      最近更新 更多