vendredi 8 septembre 2017

FormControl hide part of value

I have a parent component with a FormGroup containing several FormControls. This FormGroup also contains a custom child component which additionally adds controls to its parents FormGroup. Therefore, the child component get the formControl as input.

When the form is submitted, I'd like to add a country prefix to the child components FormControls value. Thus, the value should be saved to db with the prefix, but shown to the user without.

The problem: The child component doesn't know about the submit button. So I can't simply add the prefix when the form is submitted. And I cannot add the prefix when the user changes the value because the user would obviously see this "manipulation". And I MUST add this prefix in the child component.

My question is: Is there a way to hide a part of the FormControls value from the user? Something like pipe or a "middleware"-function I could add to the FormControl to decide, what to show to the user?

// CHILD COMPONENT
@Component({
    selector: 'app-my-comp',
    template: '<input [formControl]="inputField">'
})

export class MyComp {
    @Input() someFormGroup: FormGroup;
    inputField: AbstractControl;

    constructor(private formBuilder: FormBuilder) {
        this.inputField = formBuilder.control("", Validators.required);
        this.someFormGroup.addControl(this.inputField);
    }
}

The component is used in this component:

// PARENT COMPONENT
@Component({
    selector: 'app-parent-comp',
    template: '<form [formGroup]="someFormGroup">
                   <input [formControl]="someInputField"'
                   <app-my-comp [someFormGroup]="someFormGroup"></app-my-comp>
               </form>
})

export class MyComp {
    someFormGroup: FormGroup;
    someInputField: AbstractControl;

    constructor(private formBuilder: FormBuilder) {
        ...
    }
}




Aucun commentaire:

Enregistrer un commentaire