簡體   English   中英

如何使用formControlName 處理嵌套的formGroup?

[英]How to use formControlName and deal with nested formGroup?

正如 Angular文檔所說,我們可以在表單中使用formControlName

<h2>Hero Detail</h2>
<h3><i>FormControl in a FormGroup</i></h3>
<form [formGroup]="heroForm" novalidate>
    <div class="form-group">
        <label class="center-block">Name:
            <input class="form-control" formControlName="name">
        </label>
    </div>
</form>

像他們說的那樣...

如果沒有父 FormGroup,[formControl]="name" 可以更早地工作,因為該指令可以獨立存在,也就是說,它可以在沒有 FormGroup 的情況下工作。 對於父 FormGroup,名稱輸入需要語法 formControlName=name 才能與類中的正確 FormControl 關聯。 此語法告訴 Angular 查找父 FormGroup,在本例中為 heroForm,然后在該組中查找名為 name 的 FormControl。

無論如何,幾個月前我問這個問題是為了找出formControlName[formControl]之間的區別。

現在我的問題是:如何將formControlName與嵌套的 FormGroups 一起使用?

例如,如果我有以下表單結構:

this.myForm = fb.group({
    'fullname': ['', Validators.required],
    'gender': [],
    'address': fb.group({
        'street': [''],
        'houseNumber': [''],
        'postalCode': ['']
    })
});

使用formControlName將“street”(或“houseNumber”或“postalCode”)綁定到相關 HTML 元素的正確方法formControlName什么?

您可以使用表單組,它基本上是一組控件(控件是指在您的 html 表單中給出的字段)在您的打字稿語法中定義並使用 formControlName 指令綁定到您的 HTML 元素,例如

this.myForm = fb.group({
    'fullname': ['', Validators.required],
    'gender': [],
    'address': fb.group({
        'street': [''],
        'houseNumber': [''],
        'postalCode': ['']
    })
});

模板:

<form [formGroup]="myForm" >
   <div class="form-group">
      <label for="fullname">Username</label>
      <input type="text" id="username" formControlName="fullname" class="form-control">            
   </div>
   <div class="radio" *ngFor="let gender of genders">
      <label>
      <input type="radio" formControlName="gender" [value]="gender">{{ gender }} </label>
   </div>
   <div formGroupName="address">
      <div class="form-group">
         <label for="street">Username</label>
         <input type="text" id="username" value="street" formControlName="street" class="form-control">            
      </div>
      <div class="form-group">
         <label for="houseNumber">Username</label>
         <input type="text" id="username" value="street" formControlName="houseNumber" class="form-control">            
      </div>
      <div class="form-group">
         <label for="postalCode">Username</label>
         <input type="text" id="username" value="street" formControlName="postalCode" class="form-control">            
      </div>
   </div>
</form>

一個 formGroup 可以包含一個嵌套的 formGroup 並且層次結構可以繼續,但是在訪問值時它相當簡單。

這是真的。 查看表單組名

this.myForm = fb.group({
    'fullname': ['', Validators.required],
    'gender': [],
    'address': fb.group({
        'street': [''],
        'houseNumber': [''],
        'postalCode': ['']
    })
});

<form [formGroup]="myForm" >
   <div class="form-group">
      <label for="fullname">Username</label>
      <input type="text" id="username" formControlName="fullname" class="form-control">            
   </div>
   <div class="radio" *ngFor="let gender of genders">
      <label>
      <input type="radio" formControlName="gender" [value]="gender">{{ gender }} </label>
   </div>
   <div formGroupName="address">
      <div class="form-group">
         <label for="street">Username</label>
         <input type="text" id="username" value="street" formControlName="street" class="form-control">            
      </div>
      <div class="form-group">
         <label for="houseNumber">Username</label>
         <input type="text" id="username" value="street" formControlName="houseNumber" class="form-control">            
      </div>
      <div class="form-group">
         <label for="postalCode">Username</label>
         <input type="text" id="username" value="street" formControlName="postalCode" class="form-control">            
      </div>
   </div>
</form>

tl;博士:

您可以將表單分解為使用嵌套formgroups 的組件,並且formcontrolname可以正常使用。

我傾向於使用的方法,因為通常嵌套的表單組用於指定表單的單獨部分,是將其分解為組件並將這些組件作為輸入參數傳遞給嵌套的表單組。 所以在你的情況下,我會有一個將表單組作為參數的地址組件:

<app-address [formGroup]="myForm.get('address')"></app-address

在該組件內部,我將只有一個 @Input() formGroup 將在 html 中使用:

<div [formGroup]="formGroup">
....

這樣你就可以像往常一樣顯式地引用控件名稱,因為它是這個表單組的一部分。

另外,請記住表單是作為參考傳遞的。 您的更改將計入父組件的 myForm 元素中,如果您需要訪問不在您的表單組中的表單部分(驗證、更改檢測等),您始終可以傳遞整個表單並只定義表單組顯式引用內部組:

<div [formGroup]="formGroup.get('adress')">

(假設您傳遞整個表單對象

快樂編碼!

我正在努力解決 Angular 10 中的一個問題。我有一個“父”表單組“forma”,它有幾個依賴組:“公司”,同時,“公司”與另一個組有兩個“孩子”, msgAccounts社交媒體 當我填寫表格並提交時,在后端一切正常,我可以看到這些數據是如何正確存儲在數據庫中的,但是當我收到這個 json 時,我無法在“company.msgAccounts”和“company”中顯示數據.socialMedia”在控件(輸入)中。 這是我從服務器得到的:

            {
            name:'',
            active: '',
            ........
            company:{
              msgAccounts:{line: "@linedemo", whatsapp: "0325554244"},
              socialMedia: {fb: '', tw: '', is: ''}
             }   
            ..........
            }
    
 this.forma = this.fb.group( {
          siteName  : [ '', [Validators.required, Validators.minLength(5)]],
          siteEmail  : [ '', [Validators.required, Validators.minLength(5)]],
          // defaultLocation: [ '', [Validators.required, Validators.minLength(10)]],
          active  : [ true, [Validators.required, Validators.minLength(5)]],
          mainLanguage: ['' , [Validators.required, Validators.minLength(2)]],
        
          company: this.fb.group({
            name: [''],
            address: [''],
            phone: [''],
            msgAccounts: this.fb.group({
              line: [],
              whatsapp: []
            }),
            socialMedia: this.fb.group({
              fb: [],
              is: [],
              tw: []
            })
          })
        });
    
    And the html: (Sorry about the indentation, when it was not easy using this editor, and I just pasted a part of the code in order to do it as shorter as possible).
    
            <mat-tab-group>   
                    <mat-tab label="settings">
                        <form autocomplete="off" >
                            <ng-template ng-template matTabContent> 
                                <mat-tab-group  [formGroup]="forma">
                                        <mat-tab label="global"> 
                                           // All this fields have are fine
                                         </mat-tab>
    
                                 <mat-tab formGroupName="company" label="company"> 
                                    <div class="card">
                                        <div class="card-header" id="headingTwo">
                                            <h5 class="mb-0">Details</h5>
                                        </div>
                                        <div id="company-details">
                                                <div class="form-group row">
                                                    <div class="col-sm-3">
                                                        <input 
                                                        type="text" 
                                                        class="form-control" 
                                                        id="name" 
                                                        name="name"
                                                        placeholder="Company name"
                                                        formControlName=name>
                                                    </div>
                        
                                                </div>
    
                             <div class="form-group row" formGroupName="msgAccounts">
                                                    <div class="col-sm-6">
                                             
                                                        <input 
                                                        type="text" 
                                                        class="form-control" 
                                                        id="line" 
                                                        name="line"
                                                        placeholder="line"
                                                        formControlName=line>
                                                    </div>
                                                    <div class="col-sm-6">
                                                    
                                                        <input 
                                                        type="text" 
                                                        class="form-control" 
                                                        id="whatsapp" 
                                                        name="whatsapp"
                                                        placeholder="whatsapp"
                                                        formControlName=whatsapp>
                                                    </div>
                                                </div>
    
                                                    
    
                             <div class="form-group row" formGroupName="socialMedia" >
                         
                                                    <div class="col-sm-6">
                                                        <input 
                                                        type="text" 
                                                        class="form-control" 
                                                        id="is" 
                                                        name="is"
                                                        placeholder="Is"
                                                        formControlName=is>
                                                    </div>
                                                </div>                             
                                            </div>
                                       </div>
                                </mat-tab>                 
               </mat-tab-group>  
                            <div class="form-group row">
                            <div class="col-sm-10">
                               <button type="submit" 
                                   (click)="saveConfig()">Save</button>
                            </div>
            </div>
                        
           </ng-template>
          </form>
       </mat-tab>
    </mat-tab-group>  

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM