Angular 2 - formControlName inside component

后端 未结 7 1489
闹比i
闹比i 2020-11-30 00:21

I want to create a custom input component that I can use with the FormBuilder API. How do I add formControlName inside a component?

Template:

相关标签:
7条回答
  • 2020-11-30 01:14

    Hopefully this simple use case can help someone.

    This is an example of a phone number masking component that allows you to pass in the form group and reference the form control inside the component.

    Child Component - phone-input.component.html

    Add a reference to the FormGroup in the containing div and pass in the formControlName like you normally would on the input.

    <div [formGroup]="pFormGroup">
         <input [textMask]="phoneMaskingDef" class="form-control" [formControlName]="pControlName" >
    </div>
    

    Parent Component - form.component.html

    Reference the component and pass in pFormGroup and pControlName as atttributes.

    <div class="form-group">
         <label>Home</label>
         <phone-input [pFormGroup]="myForm" pControlName="homePhone"></phone-input>
    </div>
    
    0 讨论(0)
提交回复
热议问题