2017-12-04 14 views
0

私はテンプレート駆動型を持っています。 ngOnInitでは、サービスでフィールドデータをロードしました。角2+テンプレート駆動型設定フィールドデータ

patchValueまたはsetValueを呼び出して、フォームのフィールドにデータを格納するのに最適な場所はどれですか?

フィールドに値を設定した後、タッチまたはダーティーに変わり、検証されましたか?

ありがとうございます。ここ

+3

あなたがngModel'はちょうどあなたがテンプレート –

+0

にngModel'ディレクティブ 'に渡しているフィールドに割り当てる'使用している場合私はngModelディレクティブを使用していますが、どう思いましたか? @ViewChildで参照値をキャプチャし、モデルの値を設定しますか? – Laszlo

+0

例えば、フィールド[(ngModel)] = "sTime"のための双方向バインディングがある場合#stm = "ngModel"ここで、sTimeは文字列(フォーマットはHH:mm)であり、sTimeに値を設定しますOKですが、@ ViewChild( 'stm')でキャプチャしたngModelの触れられた&有効な値を設定しません。stmNgModel:NgModel;私はformRef.getControl(this.stmNgModel).updateValueAndValidity()を呼び出すことはできません。参照はまだ未定義であるためです。 – Laszlo

答えて

1

は、テンプレート駆動型フォームのコンポーネントのための基本の例である:

import { Component, OnInit } from '@angular/core'; 
import { NgForm } from '@angular/forms'; 
import { Router, ActivatedRoute } from '@angular/router'; 

import { IMovie } from './movie'; 
import { MovieService } from './movie.service'; 

@Component({ 
    templateUrl: './movie-edit.component.html' 
}) 
export class MovieEditComponent implements OnInit { 
    pageTitle: string = 'Edit Movie'; 
    movie: IMovie; 
    errorMessage: string; 

    constructor(private movieService: MovieService, 
     private router: Router, 
     private route: ActivatedRoute) { 
    } 

    ngOnInit(): void { 
     this.route.params.subscribe(
      params => { 
       const id = +params['id']; 
       this.getMovie(id); 
      } 
     ); 
    } 

    getMovie(id: number): void { 
     this.movieService.getMovie(id) 
      .subscribe(
      movie => this.onMovieRetrieved(movie), 
      error => this.errorMessage = <any>error); 
    } 

    onMovieRetrieved(movie: IMovie): void { 
     this.movie = movie; 
     if (this.movie.id === 0) { 
      this.pageTitle = 'Add Movie (Template-driven)'; 
     } else { 
      this.pageTitle = `Edit Movie (Template-driven): ${this.movie.title}`; 
     } 
    } 

    saveMovie(editForm: NgForm): void { 
     console.log(editForm); 
     if (editForm.dirty && editForm.valid) { 
      alert(`Movie: ${JSON.stringify(editForm.value)}`); 
     } 
    } 
} 

movieオブジェクトにデータを取得します。すべてのバインドは、movieのプロパティにバインドします。

<div class="panel panel-primary"> 
    <div class="panel-body" *ngIf='movie'> 
     <form class="form-horizontal" 
       #editForm="ngForm" 
       (ngSubmit)="saveMovie(editForm)"> 
      <fieldset> 
       <div class="form-group" 
        [ngClass]="{'has-error': (titleVar.touched || titleVar.dirty) && !titleVar.valid }"> 
        <label class="col-md-2 control-label" 
          for="inputMovieTitle">Movie Title</label> 

        <div class="col-md-8"> 
         <input class="form-control" 
           id="inputMovieTitle" 
           type="text" 
           placeholder="Title (required)" 
           required 
           minlength="3" 
           maxlength="50" 
           [(ngModel)] = "movie.title" 
           name="title" 
           #titleVar = "ngModel" /> 
         <span class="help-block" *ngIf="(titleVar.touched || titleVar.dirty) && titleVar.errors"> 
          <span *ngIf="titleVar.errors.required"> 
           Please enter a movie title. 
          </span> 
         <span *ngIf="titleVar.errors.minlength"> 
           The movie title must be at least 3 characters. 
          </span> 
         <span *ngIf="titleVar.errors.maxlength"> 
           The movie title cannot exceed 50 characters. 
          </span> 
         </span> 
        </div> 
       </div> 
      </fieldset> 
     </form> 
    </div> 
</div> 

それは全くのsetValueまたはフィールドのいずれかのマニュアルのコピーを持っていないことに注意してください。これは、双方向データバインディングとテンプレート駆動型を使用する利点です。

あなたが興味を持っている場合は、ここで、この例の完全なコードを見つけることができます:https://github.com/DeborahK/MovieHunter

+0

デボラありがとう! – Laszlo

関連する問題