惯用角度形式组件

时间:2018-02-09 21:36:17

标签: angular forms dry angular-forms

我正在创建一个使用Bootstrap输入组的表单,以允许用户输入百分比。

<div class="input-group">
  <input type="number" class="form-control" step="0.01">
  <div class="input-group-append">
    <span class="input-group-text">%</span>
  </div>
</div>

没有什么花哨,但有点冗长,我可能想要添加或修改我以后处理百分比输入的方式,所以我不想为表单上的每个百分比字段重复此HTML块。如果我正在做React,我会将它包装在一个简单的功能组件中并完成。

const PercentInput = props => (
  <div class="input-group">
    <input {...props} type="number" step="0.01">
    <div class="input-group-append">
      <span class="input-group-text">%</span>
    </div>
  </div>
);

现在我有一个PercentInput就像一个input(除了一个不同的DOM),并且不需要知道或关心它是如何使用的,因为它可以盲目地传递任何和所有道具都归结为它包装和模仿的input节点。

在Angular中创建等效组件似乎要复杂得多。据我了解,我必须做以下事情:

这看起来过于复杂,这让我觉得我陷入了React的心态,并且错过或误解了一个惯用的Angular应用程序会如何做到这一点。

在Angular中采用这种典型的干净,惯用的方法是什么?

1 个答案:

答案 0 :(得分:2)

创建一个具有Input属性字典的组件:

<强>百分比-input.component.ts

import { 
    Component, ViewChild, ElementRef, AfterViewInit, Input 
} from '@angular/core';

@Component({
    selector: 'percent-input',
    templateUrl: 'percent-input.component.html'
})
export class PercentInputComponent implements AfterViewInit {
    @ViewChild('inputField') inputField: ElementRef;
    @Input() props: { [key: string]: string };
    constructor() { }

    ngAfterViewInit() {
        if (this.props) {
            Object.keys(this.props).forEach( attr => {
                this.inputField.nativeElement.setAttribute(attr, this.props[attr]);
            });
        }
    }
}

<强>百分比-input.component.html

<div class="input-group">
    <input type="number" #inputField class="form-control" step="0.01">
    <div class="input-group-append">
        <span class="input-group-text">%</span>
    </div>
</div>

像这样使用

<percent-input [props]="{ style: 'background-color: yellow'  }" ></percent-input>

Demo

相关问题