繁体   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