Angular 2 - formControlName inside component

后端 未结 7 1542
闹比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 00:53

    Definitely worth diving deeper into @web-master-now's answer but to simply answer the question you just need the ElementRef to reference the formControlName to the input.

    So if you have a simple form

    this.userForm = this.formBuilder.group({
      name: [this.user.name, [Validators.required]],
      email: [this.user.email, [Validators.required]]
    });
    

    Then your parent component's html would be

    ...

    Then in your custom component custom-input.ts

    import { Component, Input, ViewChild, ElementRef } from '@angular/core';
    import { FormControl } from '@angular/forms';
    
    @Component({
        selector: 'custom-input',
        templateUrl: 'custom-input.html',
    })
    export class YInputItem {
    
       @Input('label') inputLabel: string;
       @Input() control: FormControl;
       @ViewChild('input') inputRef: ElementRef;
    
       constructor() { 
       }
    
       ngAfterViewInit(){
          // You should see the actual form control properties being passed in
          console.log('control',this.control);
       }
    }
    

    And then in the component's html custom-input.html

    
    
    

    Definitely worth checking out the ControlValueAccessor, but depending on how you are developing the control you might want to just use @Output to listen to change events , i.e if different inputs in the form have different events, you can just put the logic in the parent component and listen.

提交回复
热议问题