簡體   English   中英

如何設置角度形式的默認值?

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

我有一個Angular應用,其中包含處理特定表單的組件。 對於其他對象內部的各種對象,此形式相對復雜。

我想知道是否可以使用初始值重置此表單。 例如:

  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

當我調用form.reset()有一個選項可以傳遞一個默認值,但是它似乎只對頂級屬性起作用,我想為所有屬性設置默認值(一個空字符串),包括在其他對象/表單組內部更深層次的對象。

有角度的本地方法嗎? 謝謝

嗨,嘗試將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