Welcome to JiKe DevOps Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
310 views
in Technique[技术] by (71.8m points)

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);
  }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

Please log in or register to answer this question.

1 Answer

0 votes
by (71.8m points)

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);
 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to JiKe DevOps Community for programmer and developer-Open, Learning and Share

755k questions

754k answers

5 comments

53.3k users

...