简体   繁体   中英

Accessing form of child component for validation

I have an Angular 2 application in which i have a master component containing tree child components.

In one of my child components ( lets call it user_input) i have a form with user input. in my master component i have a button which needs to check if my form of the child component is valid, thus enabling it.

i have tried to access it via. (from master.view.html)

<user_input #usrInput></user_input><button                           

[disabled]="!usrInput.formname.form.valid(click)="next()">
Next</button>

But since my user_input form is not initialized at the time i validate om my master this throws an "of type unknown" exception.

Is there a clever way to solve this? i have a service shared by the two but i prefer not to use it for this.

Thanks in advance!

[UPDATE]

I have my child elements in an ngSwitch.

  <div *ngSwitchCase="0">
    <create-user-info></create-user-info>
  </div>

  <div *ngSwitchCase="1">
    <create-user-services></create-user-services>
  </div>

  <div class="col-lg-12" *ngSwitchCase="2">
    <create-user-conditions></create-user-conditions>
  </div>

</div>

once i moved it out of it the error was resolved. As i needed it to be in an ngSwitch, i used the solution kindly provided below

You could leverage the so-called safe navigation operator . This way, the following members only get evaluated, if usrInput is not null anymore.

<user_input #usrInput></user_input>
<button [disabled]="!usrInput?.formname.form.valid"
        (click)="next()">Next</button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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