简体   繁体   English

如何设置角度形式的默认值?

[英]How to set default values in angular forms?

I have an Angular app with a component that deals with a specific form. 我有一个Angular应用,其中包含处理特定表单的组件。 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. 当我调用form.reset()有一个选项可以传递一个默认值,但是它似乎只对顶级属性起作用,我想为所有属性设置默认值(一个空字符串),包括在其他对象/表单组内部更深层次的对象。

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: 嗨,尝试将formgroup放在函数之外,然后将默认值放置如下:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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