加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

数据绑定 – 组件输入属性上的双向数据绑定

发布时间:2020-12-17 07:34:03 所属栏目:安全 来源:网络整理
导读:我试图在angular2上做一些工作,我无法找到关于这种行为的东西. 我有一个实现自定义组件的应用程序,如下所示: import {Component,Input} from 'angular2/core' @Component({ selector:'my-comp',template:`input type="text" style="text-align:center; [(ng
我试图在angular2上做一些工作,我无法找到关于这种行为的东西.

我有一个实现自定义组件的应用程序,如下所示:

import {Component,Input} from 'angular2/core'
    @Component({
      selector:'my-comp',template:`<input type="text" style="text-align:center; [(ngModel)]="inputText"> <p>{{inputText}}</p>`
    })

    export class MyComp{
      @Input() inputText : string;
    }

我试图在我的组件的inputText变量上进行双向数据绑定,如下所示:

<my-comp [(inputText)]="testString"></my-comp>

其中testString是MyApp.ts中定义的包含字符串的变量.我想在我的inputText被用户修改时修改我的testString变量.

这是一个带有简单示例代码的Plunker:https://plnkr.co/edit/zQiCQ3hxSSjCmhWJMJph?p=preview

有没有办法简化这项工作?我是否必须在我的自定义组件和重载函数上实现Angular2类,以使其像ngModel一样工作?我是否必须创建一个EventEmitter类型的inputTextChanged变量,该变量在更改时发出我的数据,并执行以下操作:

<my-comp [inputText]="testString" (inputTextChanged)="testString = $event;"></my-comp>

先感谢您.

这在 Two-Way Binding with NgModel部分的模板语法文档中进行了解释:

<input [(ngModel)]="currentHero.firstName">

Internally,Angular maps the term,ngModel,to an ngModel input property and an ngModelChange output property. That’s a specific example of a more general pattern in which it matches [(x)] to an x input property for Property Binding and an xChange output property for Event Binding.

We can write our own two-way binding directive/component that follows this pattern if we’re ever in the mood to do so.

另请注意,[(x)]只是属性绑定和事件绑定的语法糖:

[x]="someParentProperty" (xChange)="someParentProperty=$event"

在你的情况下,你想要的

<my-comp [(inputText)]="testString"></my-comp>

所以你的组件必须有一个inputText输入属性和一个inputTextChange输出属性(它是一个EventEmitter).

export class MyComp {
  @Input()  inputText: string;
  @Output() inputTextChange: EventEmitter<string> = new EventEmitter();
}

要通知父级更改,每当组件更改inputText的值时,都会发出一个事件:

inputTextChange.emit(newValue);

在您的场景中,MyComp组件使用[(x)]格式将输入属性inputText绑定到ngModel,因此您使用事件绑定(ngModelChange)来通知更改,并在该事件处理程序中通知父组件更改.

在不使用ngModel的其他场景中,重要的是每当属性inputText的值在MyComp组件中发生更改时发出()一个事件.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读