How to access the control directly by its formGroupName

纵然是瞬间 提交于 2019-12-24 10:36:32

问题


In This form I have to access the control of formControlName="last" to show errors of it.

<div [formGroup]="form">
    <div formGroupName="name">
        <input formControlName="first" placeholder="First name">
        <input formControlName="last" placeholder="Last name">
        <span *ngIf="name['controls'].last.invalid">invalid</span>
    </div>
    <input formControlName="email" placeholder="Email">
    <button type="submit">Submit</button>
</div>

This code has thrown an error 'controls' of undefined(Bold Formatted line). control could be accessible by form['controls'].name['controls'].last.invalid , but is there any way I could access the control directly by its formGroupName ?

Thanks in Advance


回答1:


Try this

<div *ngIf="!form.controls.name.controls.last.valid">
       Invalid last name !!
    </div>



回答2:


Could you try below snippet

<span *ngIf="form.get('last').invalid">invalid</span>




回答3:


@sravanponugoti: we cannot use [formGroup] with in angular. Try this code

<form [formGroup]="form"> 
<div formGroupName="name"> 
<input formControlName="first" placeholder="First">
<input formControlName="last" placeholder="Last"> 
<span *ngIf="form.controls['name'].controls.last.valid">invalid</s‌​pan> 
</div> 
<input formControlName="email" placeholder="Email"> 
<button type="submit">Submit</button> 
</form>


来源:https://stackoverflow.com/questions/47301649/how-to-access-the-control-directly-by-its-formgroupname

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!