簡體   English   中英

設置ngModel默認值angular 2

[英]Setting ngModel default value angular 2

在角度為2的ngModel中遇到問題。有一項任務是從組件類中的數組輸出幾個輸入。 發現了一種可能使ngModel從[name]屬性中獲取其值而不包含[()]中的ngModel。 我想知道是否有辦法為這些輸入提供默認值。

personal-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';
    }
}

這是我的模板:

<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列出其他幾種方法,但沒有成功。

直接的方法是使用單向綁定的ngModel

<input md-input
    [placeholder]="input.placeholder"
    [type]="input.type"
    [name]="input.name"
    [disabled]="input.isDisabled"
    [required]="input.isRequired"
    [ngModel]="input.value">

它會將初始值傳遞給輸入,而不會對事件做出反應並將更改傳遞回模型。

通過添加ngModel =“{{input.defaultValue}}”來解決此問題

它應該像綁定到value屬性一樣簡單:

[value]="input.intitialValue"

或者如果不起作用:

[ngValue]="input.intitialValue"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM