Update not reflected in parent form when using ValueChanges in Angular's ControlValueAccessor

Here is the code snippet I am currently working with:

https://stackblitz.com/edit/angular-control-value-accessor-form-submitted-val-egkreh?file=src/app/app.component.html

I have set default values for the form fields, but when clicking the button, the parent form does not reflect them.

private createFormInstance() {
  this.form = this.fb.group({
    username: ['test', [Validators.required]],
    password: ['test', [Validators.required]],
  });
}

When submitting without changing any input fields, I expect to see the default values displayed, but instead, I get null. Data only shows up if I make changes to the input fields. However, there are cases where I need to submit the form with default values without making any modifications.

https://i.sstatic.net/R7TWR.png

Answer №1

Imagine a situation where your scenario closely resembles the question discussed in this post: Angular Custom Form Control - Get default value.

In your specific case, once the custom form is rendered, utilize the AfterViewInit lifecycle hook to initiate

this.form.updateValueAndValidity();

By doing so, the nested form will be updated and its default value will be transmitted to the parent form.

import { AfterViewInit } from '@angular/core';

export class LoginFormComponent
  implements ControlValueAccessor, OnInit, AfterViewInit, OnDestroy {

  ...

  ngAfterViewInit() {
    setTimeout(() => {
      this.form.updateValueAndValidity();
    })
  }
}

Check out the Demo on StackBlitz

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to incorporate a custom JavaScript file into an Angular 7 application

Suppose there is a JavaScript file named mylib.js in an angular 7 application, located at assets/mylib.js: mylib = function(){ return { hi: function() { alert('hi'); } }; }(); If I want to be able to call mylib.hi() in my hero-f ...

Tips for dynamically updating localeData and LOCALE_ID for i18n websites during the build process in Angular 9

I am currently developing an application that needs to support multiple languages, specifically up to 20 different languages. The default language set for the application is en-US. The translated versions are generated successfully during the build proces ...

What is the best way to incorporate master/detail components without relying on hierarchical routes?

I need to combine the following elements. An index page with the route /items (plural). This page should be scrollable. When clicking on individual items, I want to display a detail page with the route /item/:id (singular). The detail page should have a ...

The identity of the property cannot be located within undefined

<ion-content padding> <ion-list> <ion-item> <ion-label fixed>Username</ion-label> <ion-input type="text" value="" (ngModel)]="userData.username"></ion-input> </ion-item& ...

Removing buttons from a table row dynamically

Below is how I am adding the Button to Element: (this.sample as any).element.addEventListener("mouseover", function (e) { if ((e.target as HTMLElement).classList.contains("e-rowcell")) { let ele: Element = e.target as Element; let ro ...

Using Typescript to create an interface that extends another interface and includes nested properties

Here is an example of an interface I am working with: export interface Module { name: string; data: any; structure: { icon: string; label: string; ... } } I am looking to extend this interface by adding new properties to the 'str ...

What is the best way to implement bypassSecurityTrustResourceUrl for all elements within an array?

My challenge is dealing with an array of Google Map Embed API URLs. As I iterate over each item, I need to bind them to the source of an iFrame. I have a solution in mind: constructor(private sanitizer: DomSanitizationService) { this.url = sanitizer. ...

Tips for avoiding parent div click interference in Angular

Working with Angular8, I have a div containing a routelink along with other components including a checkbox. Here's the structure: <div [routerLink]="['/somewhere', blablabla]"> <!--other components that navigate to the ro ...

What could be the reason for TypeScript throwing an error that 'product' does not exist in type '{...}' even though 'product' is present?

Structure of Prisma Models: model Product { id String @id @default(auto()) @map("_id") @db.ObjectId name String description String price Float image String createdAt DateTime @default(now()) updatedAt Da ...

Accessing a JSON value in SCSS for localization

I have a JSON file containing all the values that I want to use for internalization in my app. On the HTML side, I am able to retrieve the values, but on the CSS side, I am using a "before" pseudo-element. In my HTML, I am using the class "menu-input" li ...

Angular version 5 and above introduces a new feature called "openFromComponent" within the Snackbar component, facilitating seamless communication

Angular (v5.2.10) Snackbar --| Introduction |-- I am facing a scenario where an Angular component named "Parent" is initializing an Angular Material Snackbar known as snackBar. The snackbar is being passed in the component called SnackbarMessage, which ...

Angular does not display results when using InnerHtml

I'm currently in the process of creating a weather application with Angular, where I need to display different icons based on the weather data received. To achieve this functionality, I have developed a function that determines the appropriate icon to ...

An error has occurred in Angular2 and Ionic 2, where there is a TypeError preventing the reading of the property 'addEventListener' in the InAppBrowser

When attempting to open a remote address in my app using the Cordova plugin InAppBrowser, I encountered an issue with the following code: import { Injectable } from "@angular/core"; import { HttpQueryService } from "./httpqueryservice"; import { ToastCo ...

Enhancing Visuals with src="imageUrl within Html"

Is there a way to customize the appearance of images that are fetched from an API imageUrl? I would like to create some space between the columns but when the images are displayed on a medium to small screen, they appear too close together with no spacing. ...

What exactly does "blocking and tackling" refer to in the Angular2 documentation?

As I delved into the online documentation for angular2, I stumbled upon a puzzling term - "blocking and tackling" in the ADVANCED - Angular Module chapter (https://angular.io/docs/ts/latest/guide/ngmodule.html). ... "It's all just basic blocking and t ...

Mixing TypeScript generic types loosely

Let's explore a simple example of typescript mixins: import { Observable, of } from 'rxjs'; class Service<TDataType> { public foo(f: TDataType): Observable<TDataType> { return of(f); } } type GConstructor<T = {}> = new ...

Which specific version of @angular/material should I be using?

After starting a new project, I encountered an issue while trying to install ng add @angular/material. The error message received was: # npm resolution error report While resolving: @angular/<a href="/cdn-cgi/l/email-protection" class="__cf_email__ ...

Enhancing the appearance of the Mui v5 AppBar with personalized styles

I am encountering an issue when trying to apply custom styles to the Mui v5 AppBar component in Typescript. import { alpha } from '@mui/material/styles'; export function bgBlur(props: { color: any; blur?: any; opacity?: any; imgUrl?: any; }) { ...

Is it possible to exclude a certain prop from a styled component that has emotions?

Within my code, there exists a component called BoxWithAs, which is defined as follows: const BoxWithAs = styled.div( { WebkitFontSmoothing: 'antialiased', MozOsxFontSmoothing: 'grayscale' // And more … } ); Everythin ...

Error encountered when trying to access children components in Typescript, even though React.FC is being

I am facing an issue with a child component that has the following structure: interface ChildProps extends AnotherInterface{ route: string, exitAction: ActionCreatorWithoutPayload, } const ChildComponent:FC<ChildProps> = ({title, shape, rout ...