Angular 4-使组件更可重用 [英] Angular 4 - make component more reusable

查看:48
本文介绍了Angular 4-使组件更可重用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使我的组件更具可重用性.在组件中,我使用ngModel绑定了两个值:elem.key和elem.value.问题是,无论我在哪里使用该组件,该元素都必须具有键和值属性,例如,来自Api的某些数据可能具有名称和昵称等.现在,我可以重复使用我的组件,但前提是值对象的关键是价值.我的代码:

I want to make my component more reusable. In the component I'm binding two values with ngModel: elem.key and elem.value. The problem is that wherever I want to use this component, the element has to have key and value properties, for example some data from Api might have name, and nickname etc. For now I can use my component repeatedly, but only if the values of object are key and value. My code:

html:

<button (click)="addNew()">Add</button>
        <div *ngFor="let elem of elements">
          <text-input [(ngModel)]="elem.key" type="text"></text-input>
          <text-input [(ngModel)]="elem.value" type="text"></text-input>
        </div>

ts:

@Input() elements: any[];

  addNew() {
    this.elements.push({
      key: '',
      value: ''
      });
    }

如果我在另一个组件中使用我的组件:

If I use my component in another:

        <input-key-value [elements]="values">

如果我只需要添加到值数组{key:``,value:''},它就可以正常工作,但是有时我想添加例如{name:``,nickname:''},导致数据在此格式必须发送到服务器.

It works fine if I only need to add to values array {key: '', value: ''} But sometimes I want to add for example {name: '', nickname: ''}, cause data in this format must be sent to the server.

我尝试添加另一个输入名称输入,{key:'name',value:'name'}并且在html中:

I tried add another Input name inputs, {key: 'name', value: 'name'} And in html:

      <text-input [(ngModel)]="elem[inputs.key]" type="text"></text-input>
      <text-input [(ngModel)]="elem.[inputs.value]" type="text"></text-input>

但这又将错误的数据推送到我的主阵列中.

But this is again pushing wrong data to my main array.

推荐答案

这对我有用.

输入键值模板:

<div *ngFor="let elem of elements">
  <div *ngFor="let prop of keys(elem)" >
    <text-input type="text" [(ngModel)]="elem[prop]"></text-input>
  </div>
</div>

输入键值ts:

keys(element) {
    return Object.keys(element);
}

根据对象具有多少个属性,它会渲染尽可能多的文本框.希望这会有所帮助.

Depending on how many properties your object has, it renders as much text boxes. Hope this will help.

这篇关于Angular 4-使组件更可重用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆