如何解决使用ngModel的问题

时间:2020-11-05 09:38:40

标签: angular

我正在尝试绑定ngModel表单输入文本,但是这里不起作用是我的 regi.component.html。 在我的html部分中,我将输入标签用于ngModel
,但是此ngModel无法打印我的字符串值

<input id="name" name="name" [(ngModel)]="hero"  >

这是我的regi.component.ts代码

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

@Component({
  selector: 'app-regi',
  templateUrl: './regi.component.html',
  styleUrls: ['./regi.component.scss']
})
export class RegiComponent implements OnInit {
hero:String ;
  constructor() { }
  ngOnInit(): void { 
this.hero = 'hello world';
}

}

就这样
我只想用html打印我的值 但是当我保存文件时
此错误显示在终端 enter image description here

这是我的regi.module.ts

import { NgModule } from '@angular/core';
import { FormsModule,ReactiveFormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';
import { RegiRoutingModule } from "./regi-routing.module";



@NgModule({
  declarations: [ ],
  imports: [CommonModule,
            FormsModule,ReactiveFormsModule,
            RegiRoutingModule],
},
)
export class RegiModule { }

保存后查看vs代码终端

这是我的项目结构
enter image description here

2 个答案:

答案 0 :(得分:0)

如果您想将表单字段与输入绑定,则不需要使用NgModel,则可以这样设置:

<input id="name" name="name" class="form-control"
      required minlength="4" appForbiddenName="bob"
      formControlName="name" >

<div *ngIf="name.invalid && (name.dirty || name.touched)"
    class="alert alert-danger">

  <div *ngIf="name.errors.required">
    Name is required.
  </div>
  <div *ngIf="name.errors.minlength">
    Name must be at least 4 characters long.
  </div>
  <div *ngIf="name.errors.forbiddenName">
    Name cannot be Bob.
  </div>

</div>

此外,您还必须在formGroup内声明此绑定到以前创建的表单:

<form [formGroup]="heroForm">
  // your form info here
</form>

答案 1 :(得分:0)

尝试在app.module.ts中导入FormsModule

 import { NgModule } from '@angular/core';
    import { FormsModule } from '@angular/forms'; 
    import { ReactiveFormsModule } from '@angular/forms';
    
    @NgModule({
      imports: [
        CommonModule,
        FormsModule,
        ReactiveFormsModule
      ], 
      declarations: []
      }
    )