angular 模拟[(ngModel)]的双向绑定 报错

代码如下

  1. app
<!-- app.component.html -->
<app-horizontal-grid 
    [(username)]="username"
></app-horizontal-grid>

[(username)]="username"位置报错:

ERROR in src/app/app.component.html:11:22 - error NG8002: Can't bind to 'username' since it isn't a known property of 'app-horizontal-grid'.

  1. If 'app-horizontal-grid' is an Angular component and it has 'username' input, then verify that it is part of this module.
  2. If 'app-horizontal-grid' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
  3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.
// app.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  username = '';
}
  1. 子组件
<!-- horizontal-grid.component.html -->`
<input 
    type="text" 
    [value]="username" 
    (input)="username = $event.target.value"
>
<span>
    hello, {{username}}
</span>
// horizontal-grid.component.ts
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-horizontal-grid',
  templateUrl: './horizontal-grid.component.html',
  styleUrls: ['./horizontal-grid.component.css']
})
export class HorizontalGridComponent implements OnInit {
  private _username: string = '';
  @Output() usernameChange = new EventEmitter();

  constructor() { }

  ngOnInit(): void {
  }

  public get username(): string {
    return this._username;
  }

  public set username(value: string) {
    this._username = value;
    this.usernameChange.emit(value);
  }

}
阅读 3k
1 个回答

ERROR in src/app/app.component.html:11:22 - error NG8002: Can't bind to 'username' since it isn't a known property of 'app-horizontal-grid'.

src/app/app.component.html:11行22列发生严重错误 ---- 错误代码:NG8002: m由于'username'并不是'app-horizontal-grid'属性,所以无法绑定。

所以原因发生在app-horizontal-grid的input上,查看该组件发现的确没有声明该input,请尝试添加@Input()注解。

@Input()
 public set username(value: string) {
   this._username = value;
   this.usernameChange.emit(value);
 }
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进