forms - 为什么 ngModel 不读取我的表单输入? ( Angular 2/4)

标签 forms angular

我正在尝试从我的 Angular 表单中获取一些输入。我想在输入时看到输入。我收到此错误:

ContactFormComponent.html:6 ERROR TypeError: Cannot read property 'name' of undefined
    at Object.View_ContactFormComponent_0._co [as updateDirectives] (ContactFormComponent.html:6)
    at Object.debugUpdateDirectives [as updateDirectives] (core.es5.js:13067)
    at checkAndUpdateView (core.es5.js:12251)
    at callViewAction (core.es5.js:12599)
    at execComponentViewsAction (core.es5.js:12531)
    at checkAndUpdateView (core.es5.js:12257)
    at callViewAction (core.es5.js:12599)
    at execComponentViewsAction (core.es5.js:12531)
    at checkAndUpdateView (core.es5.js:12257)
    at callViewAction (core.es5.js:12599)

这是我的表单 html 模板。我将 ngModel 放在表单输入中,我试图通过 {{model.name}} 绑定(bind)键入并查看我的输入。:

<div class="contact-wrap">

  <form #contactForm="ngForm" class="contact-form mx-auto">

    <label for="name">Name</label>
    <input type="text" id="name" [(ngModel)]="model.name" name="name"> {{model.name}}
    <label for="email">Email</label>
    <input type="text" id="email">
    <label for="message">Message</label>
    <textarea name="" id="message" cols="30" rows="4"></textarea >
    <input type="submit" class="contact-submit">

  </form>
</div>

这是我的表单组件:

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


@Component({
  selector: 'contact-form',
  templateUrl: './contact-form.component.html',
  styleUrls: ['./contact-form.component.scss']
})
export class ContactFormComponent implements OnInit {


  constructor() { }

  ngOnInit() {
  }


}

这是我导入 FormsModule 的 app.module.ts 的一部分:

import { FormsModule } from '@angular/forms';
  imports: [
    BsDropdownModule.forRoot(),
    BrowserModule,
    CarouselModule.forRoot(),
    RouterModule.forRoot(appRoutes),
    BrowserAnimationsModule,
    Angulartics2Module.forRoot([Angulartics2GoogleAnalytics]),
    FormsModule
  ],

此外,这里是 github repo如果您想查看所有代码。

最佳答案

首先

您不能将 undefined 分配给 [(ngModel)]

<input type="text" id="name" [(ngModel)]="model.name" name="name"> {{model.name}} </input>

所以你需要这样做:

<div *ngIf='model?.name'>
    <input type="text" id="name" [(ngModel)]="model.name" name="name"> {{model.name}} </input>
</div>

从组件端提供一些初始值,例如:

// From your component
model = { 'name' : '' };

// then your code will work fine
<input type="text" id="name" [(ngModel)]="model.name" name="name"> {{model.name}} </input>

关于forms - 为什么 ngModel 不读取我的表单输入? ( Angular 2/4),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47171360/

相关文章:

javascript - ionic 5 : Issues in changing Events to Observable

php - 如何确定通过 PHP 按下了哪个提交按钮

html - 单选按钮的样式导致页面上第一个表单之外的表单变得无响应。

javascript - 使用 laravel 后端 React Formik 文件上传

HTML 输入值

node.js - 更新 npm 到 @angular 2 不可用

angular - 升级到 Angular4 后找不到名称 'require'

javascript - PHP - 如何将错误消息返回到注册页面

css - 如何更改嵌套 Accordion 中特定 Accordion 的背景颜色?

html - 如何根据元素的内容更改元素的类?