2017-05-31 4 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

私はアイテムのリストを持っています。私は各項目のIDを取得する)。このIDは編集フォームで渡す必要があります。 –

+0

コードが動作するはずのフォームを作成するときにIDを持っている場合。 –

+0

だから私は本当になぜあなたがそれに何か変更を加えるつもりがない場合は、フォームにIDを追加したいのですか?しかし、あなたがフォームを作成し、私があなたを示したようにそれを構築する前に、このIDを持っていることを忘れないでください。 –

0

、今あなたがHTMLでそれを行っていません。フォームをビルドするときは、htmlのフォームコントロールと、可能なフォーム配列とネストされたフォームグループを使用します。ここではコードの非常に単純化されたバージョンがあります。ここではIDを非常に簡単に統合することができ、テンプレートにも含めないことにします。 :)

dbから受け取ったデータでフォームを構築するまでは、フォームを表示しないブール値フラグを使用できます。また、関数を作成し、フォームを構築するために関数を呼び出します。

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

その後のフォームを作成してみましょう:のは、だからあなたのgetProgramは(購読)コールバックでそれを呼び出しますbuildForm()それを呼ぶことにしましょう!

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 docsからFormGroup秒。

最後に、私は:)

PS上述したコードとDEMO。空のフォームが必要な場合は、コンポーネントの初期化時と同様にフォームを作成できます。あなたがデータを受信したとき、あなたは関数を呼び出すと、そのような値パッチを適用することができます

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

は、その後、もちろんブールフラグを使用しないでください。

関連する問題