设置 ngModel 默认值角度 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"

最新更新