Have a form component which contains email, password field and submit button is passed through ng-content so that for login Form 'Login' button can be showed and for register form 'Register' button can be showed. Form component template code:
<form #f="ngForm" (ngSubmit)="onSubmit(f.value)">
<div class="form-group">
<label for="email">Email</label>
<input type="email"
class="form-control"
placeholder="Enter email address"
name="email"
ngModel
>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password"
class="form-control"
placeholder="Enter the password"
name="password"
ngModel
>
</div>
<ng-content select="[submitbtn]" ></ng-content>
Code of form's parent component:
<div class="row">
<div class="col-md-6">
<!--For Login-->
<app-form-content>
<button type="submit" class="btn btn-default" submitbtn>Login</button>
</app-form-content>
</div>
<!--For register-->
<div class="col-md-6">
<app-form-content>
<button type="submit" class="btn btn-default" [disabled]="!f.valid" submitbtn>Register</button>
</app-form-content>
</div>
</div>
After run this code "TypeError: Cannot read property 'valid' of undefined" error occured. How to resolve this error?
You can't use template reference variable
#f
in parent template because its scope is the entire template where it was declared.In order to access this variable within parent template i would suggest you to declare property inside your form component:
after that you can get this property from parent template reference
#formContent
in your parent template like:Stackblitz Example