How to mark nested angular form as touched implementing ControlValueAccessor?

Discussão em 'Angular' iniciado por greatromul, Novembro 11, 2024.

  1. greatromul

    greatromul Guest

    There is an example form Angular University how to use nested forms with ControlValueAccessor.

    They create a separate form component and use it as a sub-form:

    <div [formGroup]="form">
    ... other form controls
    <address-form formControlName="address" legend="Address"></address-form>
    </div>


    I want to have all the fields of the nested form marked as touched if I call the markAllAsTouched method on the parent form.

    <form [formGroup]="form">
    <app-address-form formControlName="address"></app-address-form>
    </form>
    <button (click)="markAsTouched()">Mark as touched</button>


    export class AppComponent {
    public form: FormGroup;

    constructor(private fb: FormBuilder) {
    this.form = fb.group({ address: fb.control({ city: '' }) });
    }

    public markAsTouched() {
    this.form.markAllAsTouched();
    }
    }


    Is it possible using this approach?

    I have built a simplified version on StackBlitz.

    What actually happens when you click the button is marking the app-address-form as touched:

    <app-address-form formcontrolname="address" class="ng-pristine ng-valid ng-touched">
    ...
    </app-address-form>


    But I want to propogate it to the child form and its fields.

    Continue reading...

Compartilhe esta Página