将输入验证传递到自定义输入组件angular4中

时间:2018-06-20 00:17:24

标签: html angular typescript angular2-directives

html

<toggle-input [(text)]="selectedUser.email" placeholderText="enter user email" (textChanged)="userEmailChanged($event)"></toggle-input>

我希望能够将指令传递给此函数,以便可以将相同的输入用于不同类型的字段。一个用于信用卡号,一个用于电子邮件等。

/**
 * @class ToggleInputComponent
 * @extends BaseModal
 */
@Component({
    selector: 'toggle-input',
    templateUrl: './toggle-input.component.html',
    styleUrls: ['./toggle-input.component.scss'],
    encapsulation: ViewEncapsulation.None
})
export class ToggleInputComponent extends BaseComponent implements OnInit {
    @Input() placeholderText: string = '...enter text';
    get _placeholderText() {
        return (!this.isNullOrEmpty(this.text) ? this.text : this.placeholderText);
    }

    @Input() text: string = '';
    @Output() textChanged = new EventEmitter<string>();
    @ViewChild('editValue') editValue: ElementRef;

    private toggle: boolean = false;
    private canToggle: boolean = true;

    constructor(private searchService: SearchService) {
        super('ToggleInputComponent');
    }

    ngOnInit() {
    }

    private _onToggle(): void {
        if (this.canToggle) {
            this.toggle = !this.toggle;

            setTimeout(() => {
                if (this.toggle) {
                    this.editValue.nativeElement.focus();
                }
            }, 0);
        }
    }

    private _changeText(event: any, text: string): void {
        this.text = text;
        this.toggle = false;

        this.textChanged.emit(text);
    }

    private onKey(event: KeyboardEvent) {
        let ENTER = 13;
        let ESCAPE = 27;

        if (event.keyCode === ENTER || event.keyCode === ESCAPE) {
            this.onBlurEvent();
        }
    }

    private onBlurEvent() {
        this.toggle = false;

        this.canToggle = false;
        setTimeout(() => {
            this.canToggle = true;
        }, 150);
    }
}

基本思想是,我有一个显示值,用户名等的标签。然后,如果用户单击图标,它将更改为输入字段并允许用户输入信息。我将在各种类型的输入中使用它们,以保持应用程序的外观和风格的一致性,并且我想知道是否存在一种很好的方法来在html中的这些字段中实施错误检查。

我想动态添加一个验证指令或类似的指令。

html组件

<label *ngIf="!toggle"> {{text}} </label>
    <input #editValue class="text-input" (blur)="onBlurEvent()" value={{text}} *ngIf="toggle" type="text" (keyup)="onKey($event)" placeholder="{{_placeholderText}}" (change)="_changeText($event, editValue.value)">
    <label  class="edit-button" (click)="_onToggle()">
        <span class="edit"></span>
</label>

在此先感谢您的帮助!

0 个答案:

没有答案