gpt4 book ai didi

javascript - 如何在 Angular 2 中的无效字段上显示 'has-error' 类

转载 作者:数据小太阳 更新时间:2023-10-29 05:54:13 26 4
gpt4 key购买 nike

给定:

<div class="form-group" [fieldValidity]="email">
<label for="email" class="sr-only">Email</label>
<input [(ngModel)]="model.email" ngControl="email" required>
</div>

还有我的自定义 [fieldValidity] 指令:

import { Directive, ElementRef, Input } from 'angular2/core';
import {NgControlName} from 'angular2/common';
@Directive({
selector: '[fieldValidity]'
})
export class FieldValidityDirective {
private el: HTMLElement;
@Input('fieldValidity') field: NgControlName;
constructor(el: ElementRef) {
this.el = el.nativeElement;
}
private _onValidityChange(value: string) {
//TODO test field.valid || field.pristine
if (?) {
this.el.classList.remove('has-error');
} else {
this.el.classList.add('has-error');
}
}
}

如何订阅 field.valid && field .pristine 值以显示错误? (我在下面用'TODO'标记了它)

最佳答案

一种简单的方法是使用数据驱动方法和 [ngClass] 指令,如下所示

模板:

<form [formGroup]="form" (ngSubmit)="onSubmit()">
<div class="form-group">
<div [ngClass]="{'has-error': form.controls['description'].invalid}">
<input type="text" formControlName="description" class="form-control" required [(ngModel)]="description">
</div>
</div>
<button type="submit" class="btn btn-success">Submit</button>
</form>

组件:

export class FormComponent implements OnInit {

private form: FormGroup;
private description: string;

constructor(private formBuilder: FormBuilder) { }

ngOnInit() {
this.form = this.formBuilder.group({
description: new FormControl('')
});
}
}

关于javascript - 如何在 Angular 2 中的无效字段上显示 'has-error' 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37102343/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com