[英]Add validation class to parent element in angular 6 template driven form
Overview: 概述:
I am trying to find a nice way to add a class to an inputs parent element 我试图找到一个很好的方法来将类添加到输入父元素
I currently have this code: 我目前有这个代码:
<p [ngClass]="{'error' : prop.invalid && (prop.dirty || prop.touched) }"> <label>Prop Label</label> <input type="text" [(ngModel)]="model.prop" #prop="ngModel" required /> </p>
which works fine! 哪个工作正常!
Problem: 问题:
I want to be able to do it in a more generic way ie 我希望能够以更通用的方式做到这一点,即
Note: I am not using reactive forms 注意:我没有使用反应形式
You can add a custom attribute directive to the <p>
element that will check it's child <input>
validity. 您可以将自定义属性指令添加到
<p>
元素,该元素将检查它的子<input>
有效性。
Regarding the problems you've mentioned in your question: 关于您在问题中提到的问题:
using a directive to set the parent class
: use Renderer2
class to add/remove error
class to <p>
element using a directive to set the parent class
:使用Renderer2
类将error
类添加/删除到<p>
元素
(can't seem to find how to pass prop.invalid to it?)
: you'll get a reference to the <input>
by using @ContentChild
, finding it by NgModel
class. (can't seem to find how to pass prop.invalid to it?)
:您将通过使用@ContentChild
获取对<input>
的@ContentChild
,并通过NgModel
类查找它。
setting the parent element to receive the classes at a global level instead of the input
: not sure what is the problem, looks like the first one. setting the parent element to receive the classes at a global level instead of the input
:不确定问题是什么,看起来像第一个。 add a comment to this answer if needed. 如果需要,请在此答案中添加评论。
These are the changes you need to make: 这些是您需要做出的更改:
HTML: HTML:
<p requiredValidator>
<label>Prop Label</label>
<br>
<input type="text" [(ngModel)]="model.prop" #prop="ngModel" required />
</p>
Directive: 指示:
import { Directive, ElementRef, Renderer2, ViewChild, ContentChild, AfterContentInit } from '@angular/core';
import { NgModel } from '@angular/forms';
@Directive({
selector: '[requiredValidator]'
})
export class RequiredValidatorDirective implements AfterContentInit {
element: ElementRef;
renderer: Renderer2;
@ContentChild(NgModel) input: NgModel;
constructor(element: ElementRef, renderer: Renderer2) {
this.element = element;
this.renderer = renderer;
}
ngAfterContentInit() {
this.input.valueChanges.subscribe(() => {
if (this.input.invalid && (this.input.dirty || this.input.touched)) {
this.addErrorClass();
} else {
this.removeErrorClass();
}
})
}
addErrorClass(): void {
this.renderer.addClass(this.element.nativeElement, 'error');
}
removeErrorClass(): void {
this.renderer.removeClass(this.element.nativeElement, 'error');
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.