angular 模拟[(ngModel)]的双向绑定 报错
代码如下
- 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'.
- If 'app-horizontal-grid' is an Angular component and it has 'username' input, then verify that it is part of this module.
- If 'app-horizontal-grid' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
- 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 = '';
}
- 子组件
<!-- 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);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(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()
注解。