【发布时间】:2021-07-31 04:29:52
【问题描述】:
我目前有一个文本控件input 组件,用作我的表单的输入字段。我正在为我需要的每条输入数据重复使用它,例如姓名、邮箱、密码等
我已将组件设置为采用 required、minLength 和 maxLength(目前不显示错误,这是我的问题的一部分),并且还希望他们使用内置的 Angular 指令验证:原始、脏、触摸等,然后将在父表单组件中显示验证消息。
我无法弄清楚如何将这些指令应用于子组件的实例,因为它似乎没有到达输入字段本身,我需要将不同的指令应用于不同的实例 例如。我需要 Name 不包含数字,但我需要 Password 来包含数字,因此使用不同的指令。
text-control.component.html
<input #textControlInput readonly="{{getReadOnly()}}" className="{{getCSSClasses()}}" [id]="id" [name]="name"
[value]="modelValueDisplay" [type]="type" [minLength]="minLength" [maxLength]="maxLength" [size]="size"
[placeholder]="placeholder" [required]="required" (input)="onChange()" (change)="onChange()" />
text-control.component.ts
import {
Component,
EventEmitter,
Input,
Output,
ViewChild,
ElementRef,
} from '@angular/core';
@Component({
selector: 'app-text-control',
templateUrl: './text-control.component.html',
styleUrls: ['./text-control.component.scss'],
})
export class TextControlComponent {
@Input() className: string;
@Input() disabled = false;
@Input() form: string;
@Input() id: string;
@Input() minLength: number;
@Input() maxLength: number;
@Input() name: string;
@Input() pattern: string;
@Input() placeholder: string;
@Input() suffix: string;
@Input() size = 25;
@Input() type = 'text';
@Input() value: string;
@Input() public required = false;
@ViewChild('textControlInput') textControlInput: ElementRef;
public label: string;
touched = false;
constructor() {}
ngOnInit() {}
ngAfterViewInit() {}
getCSSClasses() {
return 'TextControl' + (this.className ? ' ' + this.className : '')
+ (this.multiLine ? ' multiLine' : '') + (this.disabled ? ' disabled' : '') ;
}
}
parent.component.html
<app-text-control id="{{idPrefix}}firstName" name="{{idPrefix}firstName" [type]="'text'" [readOnly]="readOnly"
className="g-mb-1" [size]="15" [(ngModel)]="loginDetails.firstName" [placeholder]="'First Name'"
required="true" minLength="3" maxLength="100" #firstName=ngModel>
</app-text-control>
parent.component.ts
import {
Component,
OnInit,
Input,
Output,
EventEmitter,
ViewChild,
} from '@angular/core';
@Component({
selector: 'app-form-login-details',
templateUrl: './form-login-details.component.html',
styleUrls: ['./form-login-details.component.scss'],
})
export class FormLoginDetailsComponent implements OnInit {
@Input() readOnly: boolean;
@Input() idPrefix = '';
@Input() loginDetails = new LoginDetails();
@Output() loginDetailsChange = new EventEmitter<LoginDetails>();
@Output() selectChange = new EventEmitter<any>();
constructor() {}
ngOnInit() {}
【问题讨论】:
标签: javascript html angular typescript forms