简体   繁体   中英

Angular 6 nested reactive form component

I have a component with reactive form:

@Component({
  selector: 'app-new-user',
  templateUrl: './new-user.component.html',
  styleUrls: ['./new-user.component.css']
})
export class NewUserComponent implements OnInit {

  registerForm: FormGroup;

  constructor(private formBuilder: FormBuilder) {}

  ngOnInit() {
    this.registerForm = this.formBuilder.group({
      username: [null, [Validators.required]],
      password: [null, [Validators.required]],
      isActive: [null, [Validators.required]]
    });
  }

with a template like this:

<form (ngSubmit)="onSubmit()" [formGroup]="registerForm" class="newUserForm">
      <app-form-input 
          type="text"
          formCtrlName="username">           
      </app-form-input>
      <app-form-input  
          type="password"
          formCtrlName="password">       
  </app-form-input>
  <app-form-input 
          type="checkbox"
          formCtrlName="isActive">
  </app-form-input>
</form>

As you can see inputs are wrapped in component app-form-input which looks like this:

@Component({
  selector: 'app-form-input',
  templateUrl: './form-input.component.html',
  styleUrls: ['./form-input.component.css']
})
export class FormInputComponent implements OnInit {

  @Input() type: string;
  @Input() formCtrlName: string;

  inputFormGroup: FormGroup;

  constructor(private controlContainer: ControlContainer) {}

  ngOnInit() {
    this.inputFormGroup = <FormGroup>this.controlContainer.control;
  }
}

with a template:

  <div class="form-group" [formGroup]="inputFormGroup">
          <input type={{type}}
                 formControlName={{formCtrlName}}>
    </div>

Now this nested component app-form-input works like charm when I use text based input (type="text" or type="password" works great). The problem appears when I try to use app-form-input with a type of checkbox. It renders correctly but checkbox seems to be beyond my form. It is clickable, but true/false value is never assigned to my form.

I tried to directly use in NewUserComponent form, input of type checkbox and it works like it's supposed to.

Can somebody help me spot what error have I made?

There is something wrong with when detect input type="checkbox" . Doing following trick will help you.

Change FormInputComponent HTML Like below:

<div [formGroup]="inputFormGroup" >
   <input *ngIf="type!=='checkbox'" type={{type}}
          formControlName={{formCtrlName}} >

   <input *ngIf="type==='checkbox'" type="checkbox"
          formControlName={{formCtrlName}} >
</div>

WORKING DEMO

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