微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

我的结构如下:

文件夹:my-test

> my-test.component.html
> my-test.component.css
> my-test.component.ts

1)my-test.component.html:

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐