【问题标题】:Angular2 decorator for 2 way property bindingAngular2 装饰器,用于 2 路属性绑定
【发布时间】:2016-04-20 23:11:13
【问题描述】:

来自 Victor Savkin 在Angular2 template syntax 上的帖子,展示了如何使用输入和输出属性绑定 -

<todo-cmp [model]="todo" (complete)="onCompletingTodo(todo)"></todo-cmp>

@Component({selector: 'todo-cmp'})
class TodoCmp {
  @Input() model;
  @Output() complete = new EventEmitter(); // TypeScript supports initializing fields
}

输入属性用@Input()修饰,而输出属性用@Output()修饰。 我应该如何声明一个将具有 2 路属性绑定的属性? 示例:假设 rootpanel 组件具有 'suggestions' 属性(字符串类型)并且 searchPanel 具有 'getSuggestions 属性。现在我希望这两个属性以两种方式相互绑定。 我试过了——

rootpanel.html:

<search-panel [(getSuggestions)]="suggestions"> </search-panel>

但我在 searchPanel 组件中声明 getSuggestions 属性时卡住了。 getSuggestions 属性的类型应该是什么 - string or EventEmitter&lt;string&gt;

请提出建议。

【问题讨论】:

    标签: angular angular2-directives angularjs-bindings


    【解决方案1】:

    pixelbits 推荐的方法正是您应该这样做的方法,但是如果您在一个组件上有多个双向数据绑定属性,或者甚至在您的代码库中经常更改的属性,我为此创建了一个装饰器。 如果您使用的是 npm here 它是。 需要代码的直接去 gihub 页面即可。

    有了这个,你可以直接使用:

    import { Component } from '@angular/core';
    import { TwoWay } from 'two-way-decorator';
     
    @Component({
      selector: 'app-example',
      templateUrl: './example.component.html',
      styleUrls: ['./example.component.scss']
    })
    export class ExampleComponent {
     
      @TwoWay()
      public text: string;
     
      @TwoWay()
      public count: number;
     
    }

    【讨论】:

      【解决方案2】:

      如果你想从父组件进行双向模型绑定:

      [(model)]
      

      您的子组件中需要以下内容:

      @Input() model: string;
      @Output() modelChange:EventEmitter<string>;
      

      当模型在您的子组件中被覆盖时,您将发出 modelChange 事件:

      updateModel(newValue:string) {
          this.model = newValue;
          this.modelChange.emit(this.model);
      }
      

      从父组件的角度来看,[(model)] 相当于:

      [model]="model"  (modelChange)="model=$event"
      

      这样,当模型属性在子组件内部发生变化时,模型中的变化通过双向绑定向上传播,沿途同步所有绑定的模型。

      【讨论】:

      • 感谢您的解释。
      【解决方案3】:

      如果您想使用[(getSuggestions)]-style 进行双向绑定,请声明如下字段

      class TodoCmp {
        @Input() getSuggestions;
        @Output() getSuggestionsChange = new EventEmitter(); 
      
        onClick() {
          getSuggestions = 'someValue';
          getSuggestionsChange.emit(getSuggestions);
        }
      }
      

      getSuggestions 对于这样的输入/输出组合可能不是一个好的选择,但它应该演示它们是如何连接的。输出需要与输入具有相同的名称,并带有额外的Change。 如果此命名方案不适合使用您的组件,如

      <search-panel [suggestions]="suggestions" (getSuggestions)="updateSuggestions($event)> </search-panel>
      

      输入/输出类似

      class TodoCmp {
        @Input() suggestions;
        @Output() getSuggestions = new EventEmitter(); 
      
        onClick() {
          suggestions = 'someValue';
          getSuggestions.emit(getSuggestions);
        }
      }
      

      【讨论】:

      • 谢谢,有帮助。
      猜你喜欢
      • 1970-01-01
      • 2017-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-09
      • 2020-08-27
      • 2015-09-28
      相关资源
      最近更新 更多