2017-01-25 10 views
4

角度2のngModelに問題があります。コンポーネントクラスの配列から2つの入力を出力するタスクがあります。 [()]にngModelを含めることなく、[name]属性からngModelの値を取得する可能性があります。そして、これらの入力にデフォルト値を提供する方法があるのだろうかと思います。ngModelデフォルト値の設定角度2

個人-details.component.ts:

import { 
    Component, 
} from '@angular/core'; 

import { Input }from './Input' 

@Component({ 
    selector: 'personal-details', 
    styleUrls: ['personal-details.component.sass'], 
    templateUrl: 'personal-details.component.html' 
}) 
export class PersonalDetailsComponent { 
    title: string; 
    inputs: Input[] = [ 
     new Input('Name', 'text', 'Name', true, true), 
     new Input('Surname', 'text', 'Surname', true, true), 
     new Input('Mobile phone Number', 'text', 'phone', true, true), 
     new Input('Date of Birth', 'text', 'birthday', false, true), 
     new Input('Title', 'text', 'title', false, false), 
     new Input('Title after name', 'text', 'title-after-name', false,  false), 
     new Input('Personal number', 'text', 'personal-number', false, false), 
     new Input('National ID/Passport number', 'text', 'personal-id', false, true), 
    ]; 
    save = function (form) { 
     console.log(form); 
    } 
    constructor(){ 
     this.title = 'someName'; 
    } 
} 

Here`s私のテンプレート:

<h4 class="profile__title">Personal Details</h4> 
<form #personalDetails="ngForm" (ngSubmit)="save(personalDetails.value)"> 
    <div layout="row" flex-wrap> 
     <div class="profile__input-wrapper" *ngFor="let input of inputs" flex="33"> 
      <md-input-container class="profile__input-container"> 
       <input md-input 
        [placeholder]="input.placeholder" 
        [type]="input.type" 
        [name]="input.name" 
        [disabled]="input.isDisabled" 
        [required]="input.isRequired" 
        ngModel> 
      </md-input-container> 
     </div> 
    </div> 
    <profile-footer ></profile-footer> 
</form> 

はngFor、なし成功でそれらを一覧表示するには、いくつかの他の方法を試してみました。

答えて

1

一方向結合

でngModelを使用することでしょう簡単な方法

イベントに反応して変更をモデルに戻すことなく、入力に初期値を渡します。

1

これは、value属性に結合するのと同じくらい簡単でなければなりません:

[value]="input.intitialValue" 

や問題が解決しない場合:

[ngValue]="input.intitialValue" 
+0

ありがとうございます! [ngValue]は構文エラーを返します。 [値]は有効と思われますが、実際のビューには結果が表示されません。 DOMではng-reflect-value = "1"となっていますが、 –

1

は "= {{入力をngModelを追加することで、問題を解決しました。 defaultValue}}」

+0

ああ、そう!私はあなたがngModelへの片方向バインディングを行っていることを見落としました。つまり、それを双方向のデータバインディングに変更し、それが動作します。 Sillは私のところで恋しい。 –

関連する問題