繁体   English   中英

处理 Angular 5 组件中的模型更改(双向绑定)

[英]Handle Model Change in Angular 5 Component (Two-way-binding)

我目前正在开发一个 angular 5 应用程序。 我尝试在视图的输入中更改组件的成员变量,并在更改后在组件中使用该变量。

我的结构如下:

文件夹:我的测试

  • my-test.component.html
  • 我的-test.component.css
  • 我的test.component.ts

1)我的test.component.html:

<input [(ngModel)]="hello" />

2)我的test.component.ts:

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

@Component({
  selector: 'my-test',
  templateUrl: './my-test.component.html',
  styleUrls: ['./my-test.component.css']
})
export class MyTestComponent implements OnChanges {
  hello: string = "bonjour";

  constructor() { }

  ngOnChanges(changes: SimpleChanges) {
    // I'd like to log the changes of my field 'hello', 
    // once it get's changed in the input on the ui...

       console.log(changes);
  }

}

不幸的是,这个解决方案不起作用。 您知道如何在 ui 上更改组件的变量并随后在组件中使用它吗?

谢谢!!

您可以使用 (ngModelChange) 指令

    <input [(ngModel)]="hello" (ngModelChange)="myFunction()"/>

代码:

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

    @Component({
        selector: 'my-test',
        templateUrl: './my-test.component.html',
        styleUrls: ['./my-test.component.css']
    })
    export class MyTestComponent {
        hello: string = "bonjour";

        constructor() { }

        myFunction() {
            console.log(this.hello);
        }
    }

您可以使用(ngModelChange)=functionToCall($event)在模型更改时调用函数并获取更新值。 它非常有用,您可以在同一元素[(ngModel)]其与常规[(ngModel)]一起使用。 在这种情况下,您可以仅使用[ngModel]而不是常规的[(ngModel)]并将新值设置为functionToCall函数中的变量,但这取决于您的需要。 这是一个小演示(检查控制台以查看更新的值):

https://stackblitz.com/edit/angular4-rnvmhm?file=app%2Fapp.component.html

使用框语法 [(ngModel)] 中的香蕉来获取变量 (hello) 的双向数据绑定,如果您只想在组件内的其他方法中使用 hello 变量,则无需查看值手动更改,因为ngModel将保持 property(hello) 和 view(input) 同步,因此使用 'hello' 属性的方法将始终获得更新的值。

但是如果你想在每次值改变时做一些事情,那么使用ngModelChange属性来监听属性的值变化。

<input type="text" [(ngModel)]="hello">
{{hello}}

倾听财产价值的变化

<input type="text" [(ngModel)]="hello" (ngModelChange)="executeCallback($event)">
{{hello}} //will also get updated

<input type="text" [ngModel]="hello" (ngModelChange)="executeCallback($event)">
{{hello}} //will not get updated

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM