简体   繁体   English

表单子组件的 Angular ngmodel 验证

[英]Angular ngmodel validation for a form subcomponent

I have a component and it has model like this;我有一个组件,它有这样的模型;

model={
name,
surname,
age,
birthDate
}

I pass the model to sub component我将模型传递给子组件

<form #form="ngForm" >
<input name="name" [(ngModel)]="model.name" required>
<input name="surname" [(ngModel)]="model.surname" required>
<sub-component #sub="ngModel" [(ngModel)]="model"></sub-component>
<button [disabled]="form.invalid" (click)="addOrUpdate()" ></button>
</form>

Have a sub component like this有一个像这样的子组件

<input name="age" [(ngModel)]="model.age" required>
<input name="birthDate" [(ngModel)]="model.birthDate> // not required

At parent component when i look at the validation 'sub.valid' this is always valid.在父组件中,当我查看验证“sub.valid”时,这始终有效。 But at sub component when 'model.age' is null validation is invalid.I wanted to if sub component if invalid, so parent component should be invalid.但是在'model.age'为空时的子组件验证无效。我想如果子组件无效,那么父组件应该是无效的。 Cause i want to disable parent's button.因为我想禁用父母的按钮。

I imported Control Value Accessor and provided the NG_VALUE_ACCESSOR dont fix it.我导入了控制值访问器并提供了 NG_VALUE_ACCESSOR 不修复它。 Codes are for example.代码是例如。 My model very big than this.我的模型比这个大很多。 I tried Validator interface and validate function, but it is a long way to do it.我尝试了 Validator 接口和验证函数,但这是一个很长的路要走。

Try to use form tag inside sub-component :尝试在sub-component使用表单标签:

<form #form="ngForm">
  <input name="age" [(ngModel)]="model.age" required>
  <input name="birthDate" [(ngModel)]="model.birthDate> // not required
</form>
@ViewChild('form') public form: NgForm;

In parent component template access subcomponent form to check if subcomponent's form invalid:在父组件模板中访问子组件form来检查子组件的表单是否无效:

<sub-component #sub [model]="model"></sub-component>
<button [disabled]="sub.form?.invalid" (click)="addOrUpdate()" ></button>

Hope this helps希望这可以帮助

Can i do something like this?我可以做这样的事情吗?

<form #form="ngForm">
<sub-component #sub [model]="model"></sub-component>
<button [disabled]="form.invalid" (click)="addOrUpdate()" ></button>
</form>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM