代码之家  ›  专栏  ›  技术社区  ›  Muhammed Albarmavi

实现自定义属性的双向数据绑定

  •  4
  • Muhammed Albarmavi  · 技术社区  · 7 年前

    [(selection)]="selectedItem";
    

    看起来像是

    @Input() selection;
    @Output() selection:EventEmitter<any> = new EventEmitter<any>();
    

    我如何实现这样的东西,有没有可能实现像这样的多个属性

     <component-a  [(selection)]="selectedItem"  [(data)]="selectedData"></component-a>
    
    4 回复  |  直到 7 年前
        1
  •  13
  •   Muhammad Inaam Munir    6 年前

    Angular docs

    <app-sizer 
      [(size)]="fontSizePx">
    </app-sizer>
    

    双向绑定语法实际上只是 属性绑定和事件绑定。角形脱毛器

    <app-sizer
      [size]="fontSizePx"
      (sizeChange)="fontSizePx=$event">
    </app-sizer>
    

    为属性创建双向绑定 selection 用途:

    @Input() selection;
    
    // You have to follow this convention (For Output property)
    // i.e. <propertyName><Change> like selectionChange
    
    @Output() selectionChange:EventEmitter<any> = new EventEmitter<any>();
    

    以及更改组件中的选择,如下所示:

    changeSelection(newSelection)
    {
        this.selection = newSelection;
    
        // emit change event to parent component
        this.selectionChange.emit(this.selection);  
    }
    
        2
  •  8
  •   Dmitriy Snitko    7 年前

    private _selection: any;
    get selection(): any {
        return this._selection;
    }
    @Input()
    set selection(value: any) {
        if(this._selection === value) {
            return;
        }
        this._selection = value;
        this.selectionChange.emit(this._selection);
    }
    @Output()
    selectionChange = new EventEmitter<any>();
    

    必须说出你的名字 @Output 通过添加 propertyNameChange @Input 姓名。 因此,可以在父组件模板中使用它,如下所示:

    <mycomponent [(selection)]="fieldInParentComponent"></mycomponent>
    
        3
  •  5
  •   jmdavalos    7 年前

    https://angular.io/guide/template-syntax#two-way-binding

    这个 [(x)] xChange .

    这意味着,您只需要一个对应的 selectionChange 子组件上的方法。因此,如果您希望为您的属性使用“香蕉盒子”(banana-in-a-box)绑定 selection 属于 ParentComponent ChildComponent ,请执行以下步骤:

    1. 在你的报告中包括以下内容 子组件 :

      @Input() selection;
      @Output() selectionChange = new EventEmitter<any>();
      
    2. 在你的 父组件

      <child [(selection)]="selection">
      

    总之,如果您的属性名为 x 交换 [(x)] = "parentProperty" 剩下的就交给Angular了。

        4
  •  1
  •   Sujay    7 年前

    在您的子组件(组件-a)中,您需要 @output

    @Output() change:EventEmitter = new EventEmitter();
    

    然后通过以下方式将更改的值通知父组件

    change.emit(newValue);
    

    https://stackoverflow.com/a/33220997/3710630

    推荐文章