2017-07-05 19 views
0

我有一個基本的角度組件,允許某個用戶在他們轉到他們的配置文件並單擊「編輯」後編輯用戶的詳細信息。Angular - 從服務重新填充表單輸入

組件:

export class EditUserComponent implements OnInit { 

    // Define our vars 
    user: Users[]; 
    editUserForm: FormGroup; 
    message: {}; 
    displayMessage = false; 
    userID: number; 
    errorMessage: any = ''; 

    constructor(
     private fb: FormBuilder, 
     private _userService: UserService, 
     private activatedRoute: ActivatedRoute 
    ) { 
    } 

    ngOnInit(): void { 

     // Get the userID from the activated route 
     this.activatedRoute.params.subscribe((params: Params) => { 
      this.userID = params['id']; 
     }); 

     // Call our service and pass the UserID 
     this._userService.getUser(this.userID) 
      .then(res => { 
       this.user = res; 
       this.createForm(); 
      }); 

    } 

    // Generate the form 
    createForm() { 
     this.editUserForm = this.fb.group({ 
      QID: ['', Validators.required], 
      favoriteColor: [''], 
      favoriteNumber: [''], 
      favoriteActor: [''] 
     }); 
    } 

} 

服務:

// Fetch a single user 
    getUser(userID: number) { 
     return this._http.post(this.baseUrl + '/fetchUser', { "userID": userID }, { "headers": this.headers }) 
      .toPromise() 
      .then(res => res.json()) 
      .catch(err => { this.handleError(err); }); 
    } 

接口:

export interface Users { 
    RecordID?: number; 
    QID: string; 
    favoriteColor?: string; 
    favoriteNumber?: number; 
    favoriteActor?: string; 
} 

我試圖通過值給我的formGroup,但我無法弄清楚如何訪問這些值。

我認爲我可以做這樣的事情,我可以訪問用戶模型,並從中選擇一個屬性,但是拋出一個未定義的錯誤。

我會在表單組中傳遞值,還是直接以某種方式將它們綁定到元素上?我正好從服務中收到數據,只是不確定如何將每個值返回到各自的字段。

createForm() { 
    this.editUserForm = this.fb.group({ 
     QID: [this.user.QID, Validators.required], 
     favoriteColor: [''], 
     favoriteNumber: [''], 
     favoriteActor: [''] 
    }); 
} 

回答

1

如果我理解正確的...這是我的代碼如下所示:

onProductRetrieved(product: IProduct): void { 
    if (this.productForm) { 
     this.productForm.reset(); 
    } 
    this.product = product; 

    // Update the data on the form 
    this.productForm.patchValue({ 
     productName: this.product.productName, 
     productCode: this.product.productCode, 
     starRating: this.product.starRating, 
     description: this.product.description 
    }); 
    this.productForm.setControl('tags', this.fb.array(this.product.tags || [])); 
} 

我對數值使用patchValue,對數組使用setControl

OR

由於您檢索數據後創建的形式,你可以做這樣的事情:

createForm() { 
    this.editUserForm = this.fb.group({ 
     QID: [this.user.QID, Validators.required], 
     favoriteColor: [this.user.favoriteColor], 
     favoriteNumber: [this.user.favoriteNumber], 
     favoriteActor: [this.user.favoriteActor] 
    }); 
} 

,只是要完整...每個輸入元素需要一個formControlName性質類似這樣的:

    <input class="form-control" 
          id="productNameId" 
          type="text" 
          placeholder="Name (required)" 
          formControlName="productName" /> 
        <span class="help-block" *ngIf="displayMessage.productName"> 
          {{displayMessage.productName}} 
        </span> 
       </div> 

您可以在這裏找到一個完整的工作示例:https://github.com/DeborahK/Angular2-ReactiveForms

+0

所以你的第二個使用'this.user.QID'的例子是我理想的解決方案,並且是我首先嚐試的,但是我在'Users []'類型'中找不到'Property'QID'的錯誤。「我認爲它是正確的,因爲它在我的界面中定義。 – SBB

+0

這正是它所說的嗎?如果是這樣,那麼它認爲'this.user'是一個數組。你是否從'getUser'獲得數組而不是獲取單個用戶? – DeborahK

+0

噢......我看到了......你把它聲明爲一個頂部數組:'user:Users [];'如果它不應該是一個數組,那麼將它改爲'user:Users'(沒有數組)。 – DeborahK

0

綁定一個事件提交到表單,然後使用this.editUserForm.value從表單訪問數據。

分量模板:

<form [formGroup]="editUserForm" (submit)="saveIt()"> 

在Component:

saveIt() { 
    if (this.editUserForm.dirty && this.editUserForm.valid) { 
     alert(`Number: ${this.editUserForm.value.favoriteNumber} Actor: ${this.editUserForm.value.favoriteActor}`); 
    } 
    } 
+0

這看起來像反應形式...所以沒有必要從模板中傳遞它。 – DeborahK

+0

我不想讓輸入的值進入表單。該頁面有幾個輸入字段,我需要從數據庫中填寫(服務調用),以便可以更新它們。本質上,我將這些字段的值設置爲從數據庫中提取的值。 – SBB