st_*_*rke 7 javascript angular2-forms typescript1.8 angular
我想将父组件的FormGroup传递给它的子组件,以便使用子组件显示错误消息
鉴于以下父母
import { Component, OnInit } from '@angular/core'
import {
REACTIVE_FORM_DIRECTIVES, AbstractControl, FormBuilder, FormControl,
FormGroup, Validators
} from '@angular/forms'
@Component(
{
moduleId: module.id,
selector: 'parent-cmp',
templateUrl: 'language.component.html',
styleUrls: ['language.component.css'],
directives: [
ErrorMessagesComponent]
})
export class ParentCmp implements OnInit {
form: FormGroup;
first: AbstractControl;
second: AbstractControl;
constructor(private _fb: FormBuilder) {
this.first =
new FormControl('');
this.second = new FormControl('')
}
ngOnInit() {
this.form = this._fb.group(
{
'first': this.first,
'second': this.second
});
}
}
Run Code Online (Sandbox Code Playgroud)
import { Component, OnInit, Input } from '@angular/core'
import { NgIf } from '@angular/common'
import {REACTIVE_FORM_DIRECTIVES, FormGroup } from '@angular/forms'
@Component(
{
moduleId: module.id,
selector: 'epimss-error-messages',
template: `
<span class="error" *ngIf="errorMessage !== null">{{errorMessage}}</span>`,
styles: [],
directives: [REACTIVE_FORM_DIRECTIVES, NgIf]
})
export class ErrorMessagesComponent implements OnInit {
@Input()
ctrlName: string
constructor(private _form: FormGroup) {
}
ngOnInit() {
}
get errorMessage() {
// Find the control in the Host (Parent) form
let ctrl = this._form.find(this.ctrlName);
console.log('ctrl| ', ctrl)
// for (let propertyName of ctrl.errors) {
// // If control has a error
// if (ctrl.errors.hasOwnProperty(propertyName) && ctrl.touched) {
// // Return the appropriate error message from the Validation Service
// return CustomValidators.getValidatorErrorMessage(propertyName);
// }
// }
return null;
}
Run Code Online (Sandbox Code Playgroud)
我想在http://iterity.io/2016/05/01/angular/angular-2-forms-and-advanced-custom-validation/上关注这个过时的例子.
Pet*_*ris 14
在父组件中执行此操作
<div [formGroup]="form">
<div>Your parent controls here</div>
<your-child-component [FormGroup]="form"></your-child-component>
</div>
Run Code Online (Sandbox Code Playgroud)
然后在您的子组件中,您可以像这样获得该引用...
export class YourChildComponent implements OnInit {
public form: FormGroup;
// Let Angular inject the control container
constructor(private controlContainer: ControlContainer) { }
ngOnInit() {
// Set our form property to the parent control
// (i.e. FormGroup) that was passed to us, so that our
// view can data bind to it
this.form = <FormGroup>this.controlContainer.control;
}
}
Run Code Online (Sandbox Code Playgroud)
您甚至可以通过更改其选择器来确保组件中的任何一个formGroupName或[formGroup]在组件上指定.
selector: '[formGroup] epimss-error-messages,[formGroupName] epimss-error-messages'
Run Code Online (Sandbox Code Playgroud)
这个答案应该足以满足您的需求,但如果您想了解更多,我在这里写了一篇博客文章
Kir*_* G. 13
对于 Angular 11,我尝试了上述所有答案以及不同的组合,但没有任何对我有用。所以我最终得到了以下解决方案,它按照我的意愿为我工作。
打字稿
@Component({
selector: 'fancy-input',
templateUrl: './fancy-input.component.html',
styleUrls: ['./fancy-input.component.scss']
})
export class FancyInputComponent implements OnInit {
valueFormGroup?: FormGroup;
valueFormControl?: FormControl;
constructor(
private formGroupDirective: FormGroupDirective,
private formControlNameDirective: FormControlName
) {}
ngOnInit() {
this.valueFormGroup = this.formGroupDirective.form;
this.valueFormControl = this.formGroupDirective.getControl(this.formControlNameDirective);
}
get controlName() {
return this.formControlNameDirective.name;
}
get enabled() {
return this.valueFormControl?.enabled
}
}
Run Code Online (Sandbox Code Playgroud)
超文本标记语言
<div *ngIf="valueFormGroup && valueFormControl">
<!-- Edit -->
<div *ngIf="enabled; else notEnabled" [formGroup]="valueFormGroup">
<input class="input" type="text" [formControlName]="controlName">
</div>
<!-- View only -->
<ng-template #notEnabled>
<div>
{{valueFormControl?.value}}
</div>
</ng-template>
</div>
Run Code Online (Sandbox Code Playgroud)
用法
请注意,我必须添加ngDefaultControl,否则它不会在控制台中给出默认值访问器错误(如果有人知道如何在没有错误的情况下摆脱它 - 将不胜感激)。
<form [formGroup]="yourFormGroup" (ngSubmit)="save()">
<fancy-input formControlName="yourFormControlName" ngDefaultControl></fancy-input>
</form>
Run Code Online (Sandbox Code Playgroud)
小智 7
这是在父 formGroup 中使用的子组件的示例:子组件 ts:
import { Component, OnInit, Input } from '@angular/core';
import { FormGroup, ControlContainer, FormControl } from '@angular/forms';
@Component({
selector: 'app-date-picker',
template: `
<mat-form-field [formGroup]="form" style="width:100%;">
<input matInput [matDatepicker]="picker" [placeholder]="placeHolder" [formControl]="control" readonly>
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>
</mat-form-field>
<mat-icon (click)="clearDate()">replay</mat-icon>`,
styleUrls: ['./date-picker.component.scss']
})
export class DatePickerComponent implements OnInit {
public form: FormGroup;
public control : FormControl;
@Input() controlName : string;
@Input() placeHolder : string;
constructor(private controlContainer: ControlContainer) {
}
clearDate(){
this.control.reset();
}
ngOnInit() {
this.form = <FormGroup>this.controlContainer.control;
this.control = <FormControl>this.form.get(this.controlName);
}
}
Run Code Online (Sandbox Code Playgroud)
css日期选择器:
mat-icon{
position: absolute;
left: 83%;
top: 31%;
transform: scale(0.9);
cursor: pointer;
}
Run Code Online (Sandbox Code Playgroud)
并像这样使用:
<app-date-picker class="col-md-4" [formGroup]="feuilleForm" controlName="dateCreation" placeHolder="Date de création"></app-date-picker>
Run Code Online (Sandbox Code Playgroud)
父组件:
@Component({
selector: 'app-arent',
templateUrl: `<form [formGroup]="parentFormGroup" #formDir="ngForm">
<app-child [formGroup]="parentFormGroup"></app-child>
</form> `
})
export class ParentComponent implements {
parentFormGroup :formGroup
ngOnChanges() {
console.log(this.parentFormGroup.value['name'])
}
}
Run Code Online (Sandbox Code Playgroud)
子组件:
@Component({
selector: 'app-Child',
templateUrl: `<form [formGroup]="childFormGroup" #formDir="ngForm">
<input id="nameTxt" formControlName="name">
</form> `
})
export class ChildComponent implements OnInit {
@Input() formGroup: FormGroup
childFormGroup :FormGroup
ngOnInit() {
// Build your child from
this.childFormGroup.addControl('name', new FormControl(''))
/* Bind your child form control to parent form group
changes in 'nameTxt' directly reflect to your parent
component formGroup
*/
this.formGroup.addControl("name", this.childFormGroup.controls.name);
}
}
Run Code Online (Sandbox Code Playgroud)
Mil*_*lad -1
我会将表单作为输入传递给子组件;
@Component(
{
moduleId: module.id,
selector: 'epimss-error-messages',
template: `
<span class="error" *ngIf="errorMessage !== null">{{errorMessage}}</span>`,
styles: [],
directives: [REACTIVE_FORM_DIRECTIVES, NgIf]
})
export class ErrorMessagesComponent implements OnInit {
@Input()
ctrlName: string
@Input('form') _form;
ngOnInit() {
this.errorMessage();
}
errorMessage() {
// Find the control in the Host (Parent) form
let ctrl = this._form.find(this.ctrlName);
console.log('ctrl| ', ctrl)
// for (let propertyName of ctrl.errors) {
// // If control has a error
// if (ctrl.errors.hasOwnProperty(propertyName) && ctrl.touched) {
// // Return the appropriate error message from the Validation Service
// return CustomValidators.getValidatorErrorMessage(propertyName);
// }
// }
return null;
}
Run Code Online (Sandbox Code Playgroud)
当然,您需要将表单从父组件传递给子组件,您可以通过不同的方式执行此操作,但最简单的是:
在你父母的某个地方;
<epimss-error-messages [form]='form'></epimss-error-messages>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13003 次 |
| 最近记录: |