[英]Angular 4 Readonly input change detection
I have following code with readonly input. 我有以下带有只读输入的代码。 am trying to change the value if this readonly input from TS File, but, I am unable to detect change from any function.
我正在尝试从TS File的此只读输入更改值,但是,我无法检测到任何功能的更改。 Below is the example.
以下是示例。
<input type="text" class="form-control" id="field1" name="field1" readonly [(ngModel)]="field1" (ngModelChange)="onChange()">
ngModelChange is not working in this senario. ngModelChange在此Senario中不起作用。
You can try to use the (change)
instead of (ngModelChange)
. 您可以尝试使用
(change)
而不是(ngModelChange)
。
Here is some explanation to help you understand this. 这里有一些解释可以帮助您理解这一点。
Use input like this: 使用这样的输入:
(input)="handle($event)"
And Handle event in your typescript accordingly. 并相应地在打字稿中处理事件。
FormControl
to the rescue!! FormControl
进行救援!!
FormControls and Reactive forms are great and it will save your day! FormControls和Reactive表单很棒,它将节省您的时间! :)
:)
Mark ReactiveFormsModule
in your app.module, import FormControl
to your component aaand... For demo I used a simple timeout to change the value to trigger the valueChanges
: 在您的app.module中标记
ReactiveFormsModule
,将FormControl
导入到您的组件aaand ...对于演示,我使用了一个简单的超时来更改值以触发valueChanges
:
myControl = new FormControl('')
constructor() { }
ngOnInit() {
setTimeout(() => {
this.myControl.setValue('something');
}, 2000);
this.myControl.valueChanges.subscribe((data) => {
console.log('changed!')
});
}
And template: 和模板:
<input type="text" readonly [formControl]="myControl">
PS if this is input is part of a template driven form, this wouldn't work, since ngModel
and formControl
shouldn't be used together. PS,如果输入此内容是模板驱动的表单的一部分,则这将无法工作,因为
ngModel
和formControl
不应一起使用。 So you would be notified of that. 因此,您将收到通知。 So in that case I suggest you go reactive way ;)
因此,在这种情况下,我建议您采取被动方式;)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.