简体   繁体   English

Angular2-重用HTML

[英]Angular2 - Reuse HTML

I'm working on a business UI with many forms and each form is composed of many elements. 我正在使用具有多种形式的业务UI进行工作,每种形式都由许多元素组成。 Using bootstrap each element looks like : 使用引导程序,每个元素看起来像:

<div class="form-group">
   <label for="userName" class="col-sm-3 control-label">User name</label>
   <div class="col-sm-9">
       <input type="text" class="form-control" id="userName" name="userName" placeHolder="User Name" [(ngModel)]="myObj.username">
   </div>
</div>

And this is omitting the validation part... So I'm afraid this is getting out of hand and any change will have to be copy/pasted to fix all those inputs. 而且这省略了验证部分...因此,我担心这会变得一发不可收拾,任何更改都必须复制/粘贴以修复所有这些输入。

I've tried creating an "input component" that would be smart enough to do the proper HTML depending on a few parameters like the id, the text to display but I can't get the [(ngModel)] to work with this solution. 我尝试创建一个“输入组件”,该组件足够聪明,可以根据一些参数(如id,要显示的文本)执行正确的HTML,但是我无法使[(ngModel)]与该解决方案一起使用。

Any good solution to handle this ? 有什么好的解决办法吗? Or do I have to accept my doom and copy/paste everywhere ? 还是我必须接受我的厄运并在各处复制/粘贴?

Thanks @Günter for pointing in an helpful direction. 感谢@Günter指出了有用的方向。

Following your lead I found https://blog.thoughtram.io/angular/2016/07/27/custom-form-controls-in-angular-2.html and ended up with a working solution where: 在您的领导下,我找到了https://blog.thoughtram.io/angular/2016/07/27/custom-form-controls-in-angular-2.html并最终得到了一个可行的解决方案,其中:

  • my inputComponent.html always has [(ngModel)]="value" 我的inputComponent.html始终具有[(ngModel)] =“ value”
  • inputComponent.ts has a setter and a getter for the value attribute. inputComponent.ts具有value属性的设置器和获取器。

Then I can implement the getter/setter to write in my data model. 然后,我可以实现将getter / setter写入我的数据模型。


In my form : 以我的形式:

 <app-input [type]="'text'" [id]="'username'" [model]="mymodel" ></app-input>

My inputComponent.html like : 我的inputComponent.html像:

 <input *ngIf="type == 'text' [(ngModel)]="value" />

My inputComponent.ts : 我的inputComponent.ts:

 get value():any{
    return this.model[this.id];
 }

 set value(val){
    this.model[this.id] = val;
 }

It is not perfect as if the model's value changes outside the form it will not show but it is not needed for my purpose. 好像模型的值超出它不会显示的形式而变化,但出于我的目的不是必需的,这不是完美的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM