简体   繁体   中英

How to set default values in angular forms?

I have an Angular app with a component that deals with a specific form. This form is relatively complex with various objects inside other objects.

I would like to know if it´s possible to reset this form with the initial value. For example:

  createForm() {
    this.form = this.fb.group({
        id: [''],
        category: ['', Validators.compose([
            Validators.required,
            Validators.minLength(3),
            Validators.maxLength(64)
        ])],        
        user: this.fb.group({
            username: ['', Validators.compose([
                Validators.required,
                Validators.minLength(3),
                Validators.maxLength(13000)
            ])],
            lastname: ['', Validators.compose([
              Validators.required,
              Validators.minLength(2),
              Validators.maxLength(64)
            ])]

      // ...and so on

When I call the form.reset() there´s an option to pass a default value, but it only seems to work to the top level properties, I would like to set the default value (an empty string) to all properties including the ones which are in a deep level inside of other objects/formgroups.

Is there a native way in angular to do it? Thanks

hi try to put the formgroup outside the function and place the default value like this:

this.form = this.fb.group({
    id: ['sampleId'],
    category: ['sampleCat', Validators.compose([
        Validators.required,
        Validators.minLength(3),
        Validators.maxLength(64)
    ])],        
    user: this.fb.group({
        username: ['sampleUsername', Validators.compose([
            Validators.required,
            Validators.minLength(3),
            Validators.maxLength(13000)
        ])],
        lastname: ['sampleLastname', Validators.compose([
          Validators.required,
          Validators.minLength(2),
          Validators.maxLength(64)
        ])]

  // ...and so on

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM