简体   繁体   中英

Angular how to add a form group to a TR component?

I have a table that is looping over an array of form control values.

<tbody>
  <tr *ngFor="let t of intakeForm.get('tasks').value let i = index; trackBy:trackByIndex" [taskTR]="t" [ui]="uiOptions" [intakeForm]="intakeForm"></tr>
</tbody>

Within my TR component, the HTML is all of the TD data, pretty standard stuff.

However, I have an input within one of those TD's that I need to assign a formControlName to.

When I try and do this, it tells me that it needs to be within a formGroup which I totally understand.

However, if I try and wrap all the TD's with a formGroup div, it makes the table HTML invalid.

TR Component HTML:

<td>{{ row.User.FirstName }} {{ row.User.LastName }}</td>
<td>{{ row.Tool.ToolName }}</td>
<td class="col-md-9">
    <ng-select  [items]="ui.adminRoles.options" 
                bindLabel="RoleName" 
                bindValue="Role"
                placeholder="Select one or more roles" 
                [multiple]="true"
                [clearable]="false" 
                (add)="addRole($event, row)" 
                formControlName="someField"
                (remove)="removeRole($event, row)">
    </ng-select>
</td>

The above results in the error:

ERROR Error: formControlName must be used with a parent formGroup directive.  You'll want to add a formGroup
       directive and pass it an existing FormGroup instance (you can create one in your class).

How could I add a form group to this while still keeping the HTML valid? ie, a div inside a table row is not valid syntax.

For using FormGroup -Elements in your template, you should set FormGroup -Directive. The easiest way to do this is to wrap your table with form -Tag and add FromGroup -Directive to this form -Tag. Like this:

<form [formGroup]="yourFormGroup">
  <tbody>
    <tr *ngFor="let t of intakeForm.get('tasks').value let i = index; trackBy:trackByIndex" [taskTR]="t" [ui]="uiOptions" [intakeForm]="intakeForm">    </tr>
  </tbody>
</form>

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