Wrapping angular reactive form component with validator

后端 未结 2 615
孤街浪徒
孤街浪徒 2021-02-06 15:04

Working with angular 7 and Bootstrap 4, I want to wrap my bootstrap 4 inputs in a custom component in order to reduce the boilerplate in my templates.

I want that the fi

2条回答
  •  旧巷少年郎
    2021-02-06 15:09

    The "key" is using viewProvider. You use a @Input set to give value to a formControl, see stackblitz. The "magic" is that if equal refered to formControl in the "children" or form.get('input1') in the parent

    @Component({
      selector: 'app-form-control',
      template: `
      
    {{formControl.valid}}{{formControl.touched}}} `, viewProviders: [{ provide: ControlContainer, useExisting: FormGroupDirective }]}) export class HelloComponent { formControl: FormControl; constructor(private parentF: FormGroupDirective) { } @Input() set controlName(value) { this.formControl = this.parentF.form.get(value) as FormControl } @Input() label: string; @Input() placeholder: string; }

    And call the component this way:

    Update well, (after a year) take account the stackblitz was erroneous. when you (click) in buttons create a new Form:

     this.form=this.createForm({note:'lll'})
    

    This "break" the relationship between the component and the form because the relation is about the older form -only change if change the @Input "nameControl". So the correct is use a setValue to give a new value to the form.

提交回复
热议问题