2017-05-31 42 views
0

我想通過傳遞的ID更新數據庫中的一行。如何使用FormBuilder傳遞對象的id更新

我有一個表單組件,你可以看到我用的反應formBuilder:

@Component({ 
    selector: 'program-form', 
    templateUrl: './program.form.component.html', 
    styleUrls: ['./program.form.component.css'] 
}) 
export class ProgramFormComponent implements OnInit { 

    form: FormGroup; 
    title: string; 
    program: ProgramModel = new ProgramModel(); 

    constructor(
    formBuilder: FormBuilder, 
    private router: Router, 
    private route: ActivatedRoute, 
    private dataService: DataService 
) { 
    this.form = formBuilder.group({ 
     name: ['', [ 
     Validators.required, 
     Validators.minLength(3) 
     ]], 
    // email: ['', [ 
    //  Validators.required, 
    //  BasicValidators.email 
    // ]], 
    // phone: [], 
    // address: formBuilder.group({ 
    //  street: ['', Validators.minLength(3)], 
    //  suite: [], 
    //  city: ['', Validators.maxLength(30)], 
    //  zipcode: ['', Validators.pattern('^([0-9]){5}([-])([0-9]){4}$')] 
    // }) 
    }); 
    } 

    ngOnInit() { 
    var id = this.route.params.subscribe(params => { 
     var id = params['id']; 

     this.title = id ? 'Edit' : 'New'; 

     if (!id) 
     return; 

     this.getProgram(id); 
    }); 
    } 

    private getProgram(id: number) { 
     this.dataService.setEndpoint('/api/program/getsingle'); 
     this.dataService 
      .GetSingle(id) 
      .subscribe(data => { 
       this.program = data 
      }, (error) => { 
       console.log(error); 
      }); 
    } 

    create() { 
    var result, 
     userValue = this.form.value; 

     console.log(userValue.Id + ", userValueId"); 

    if (userValue.id){ 
     this.dataService.setEndpoint('/api/program/update'); 
     result = this.dataService.Update(userValue.Id, userValue); 
    } 
    else 
    { 
     this.dataService.setEndpoint('/api/program/create'); 
     this.dataService.Create(userValue).subscribe(data => { 
       (data => this.router.navigate(['users'])); 
      }, (error) => { 
       console.log(error); 
      });; 
    } 

    //result.subscribe(data => this.router.navigate(['users'])); 
    } 
} 

HTML:

<div class="row"> 
    <form materialize class="col s12" [formGroup]="form" (ngSubmit)="create()"> 
    <div class="row"> 
     <div class="input-field col s12"> 
     <i class="material-icons prefix">account_circle</i> 
     <label for="name" 
       [class.active]="program.name" 
       data-error="Name is required and needs to contain at least 3 chars"> 
      Name 
     </label> 
     <input id="name" type="text" class="validate" 
       [(ngModel)]="program.name" formControlName="name" 
       [class.invalid]="form.controls['name'].touched && !form.controls['name'].valid"> 
     </div> 
    </div> 

    <button class="btn waves-effect waves-light" type="submit"> 
     Submit<i class="material-icons right">send</i> 
    </button> 
    </form> 
</div> 

如何從this.form.value爲您檢索ID可以看到我試圖獲得id,但console.log說它是未定義的。我是否需要在表單構建器或html內部初始化它?

+0

哪裏有id?我看不到任何你想傳遞它的地方?'我瞎了嗎:D – Alex

+0

你甚至沒有在你的html中使用formbuilder? – Alex

+0

你能解釋一下嗎?我不確定你的意思。 –

回答

0

看來你沒有在窗體本身上的Id應該用戶輸入這個ID或從哪裏得到它?

如果你想成爲在表格上,你將不得不添加到窗體團,如:

id: [id ||''], 
name: ['', [... 
+0

我有一個項目列表,然後點擊Edit(so我爲每個項目獲得Id)。這個ID應該以編輯的形式傳遞。 –

+0

如果您在創建代碼應該工作的表單時擁有該ID。 –

+0

所以我真的不明白你爲什麼要添加id到表單中,如果你不做任何修改的話。但是如果你想這樣做,記得在創建表單之前擁有這個id,並像我向你展示的那樣構建它。 –

0

你其實應該利用你所創建的反應形式,現在你還沒有這樣做,在你的HTML 。當你創建一個表單時,你可以在你的html中使用表單控件,以及任何可能的表單數組和嵌套表單組。這裏是你的代碼的一個非常簡化的版本,我們可以很容易地集成這個id,我們只是決定不將它包含在模板中! :)

您可以使用不顯示錶單的布爾標誌,直到我們用您從db接收的數據構建它。此外,我們創建一個函數,我們稱之爲構建表單。讓我們把它buildForm()所以你getProgram將調用回調(訂閱):

.subscribe(data => { 
    this.program = data; 
    this.buildForm(); // here! 
}, ... 

然後讓我們構建的形式!

buildForm() { 
    this.form = this.formBuilder.group({ 
    id: [this.program.id] 
    name: [this.program.name] 
    }); 
    this.isDone=true; // set boolean flag true so that the form will be shown! 
} 

現在轉到表單,我們實際使用了我們創建的表單控件。在這裏,我們可以排除表單控件id,它仍然有價值,我們只是不顯示它。注意使用formControlName

<form [formGroup]="form" *ngIf="isDone" (ngSubmit)="create(form.value)"> 
    <input formControlName="name" /> 
    <button type="submit">Submit</button> 
</form> 

這就是它!當您現在控制檯記錄表單值時,它也會包含該ID。

瞭解更多關於反應形式,formControl:S,FormArray:S和來自本official docsFormGroup秒。

最後一個DEMO與我上述:)

PS所描述的代碼。如果你需要一個空的表單,你可以像組件初始化時那樣構建它。然後當你收到數據時,你可以調用一個函數並修改數值,如下所示:

this.form.patchValue({ 
    id: this.program.id, 
    name: this.program.name 
}) 

然後當然不要使用布爾標誌。