设置 ngModel 默认值 angular 2

Setting ngModel default value angular 2

angular 中的 ngModel 有问题 2. 有一个任务要从组件 class 中的数组输出几个输入。 发现了一种使 ngModel 从 [name] 属性中获取其值而不包含 [()] 中的 ngModel 的可能性。我想知道是否有办法为这些输入提供默认值。

个人-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 列出它们的方法,但没有成功。

它应该像绑定到值属性一样简单:

[value]="input.intitialValue"

或者如果这不起作用:

[ngValue]="input.intitialValue"

通过添加 ngModel="{{input.defaultValue}}"

解决了这个问题

最简单的方法是使用带有 one-way 绑定的 ngModel

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

它会将初始值传递给输入,而不会对事件做出反应并将更改传递回模型。