代码之家  ›  专栏  ›  技术社区  ›  Fallenreaper

使用变量而不是使用发射器的双向绑定?

  •  1
  • Fallenreaper  · 技术社区  · 6 年前

    我想我需要利用AngularTS组件中的子组件中的输出注释来更改父属性,但我想我可以这样做: [(item)]="myItem" 它会正确绑定。

    我在查看输出和EventEmitter,但这是在创建新的变量,这些变量只被监视以执行以下函数:

    @Output() clicked = new EventEmitter<number>();
    

    (clicked)="myFunc(id)"
    

    考虑到我的用例,我认为不需要输出,因为我没有执行父级中定义的函数等,只是想更新属性, 我的项目 在这种情况下。

    关于如何绑定以及是否应该使用输出注释,这是正确的思考过程吗?

    组件1 HTML:

    <sub-component [(selection)]="selection"></sub-component>
    

    组件1 TS:

    export class MyComponent implements OnInit {
        @Input() selection: string = "";
        @Output() selectionChange: EventEmitter<string> = new EventEmitter<string>();
    }
    

    子组件HTML:

    <div></div>
    

    子组件TS:

    export class SubComponent implements OnInit {
        @Input() selection: string;
        @Output() selectionChange: EventEmitter<string> = new EventEmitter<string>();
    
        doStuff(): void {
          this.selection = "test";
          this.selectionChange.emit(this.selection);
        }
    }
    

    问题是MyComponent有一个selection属性,但它从来没有在其中赋值,它实际上只是将它传递到更高的级别,因此由于它没有在代码中设置,所以我不能说: selectionChange.emit(this.selection); . 给出一些答案,我该如何解决这个概念?它会自动传递,还是我必须创建某种StreamListener来监视变量更改?

    3 回复  |  直到 6 年前
        1
  •  2
  •   Reza    6 年前

    Change myInput 发出更改事件。

    @Input() myInput : type;
    @Output() myInputChange: EventEmitter<type> = new EventEmitter<type>();
    

    <my-component [(myInput)]="input"></my-component>
    

    banana-in-The-box语法只是一个类似于下面的语法糖

    <my-component [myInput]="input" (myInputChange)="input=$event"></my-component>
    

    注意这是给你的 Components Services

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

        2
  •  0
  •   Aniruddha Das xing    6 年前

    双向数据绑定 ([clicked]) 只在组件内部工作。因为您的需求是在父组件和子组件之间进行通信,所以您需要一些能够让父组件或子组件知道另一个组件中发生了更改的内容。

    另外,双向数据绑定主要用于从视图到模型的通信(显然是按照angular 1.x.x),而不是用于从父组件到子组件的通信,这与angular 1.x.x和angular+2.x.x不同

    在您的情况下,您可以使用 EventEmitor @Output RxJs Subject .

        3
  •  0
  •   Dmitriy Snitko    6 年前

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

    一个好方法是使用属性集方法来发出更改事件:

    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>
    

    mycomponent公司

    <subchildcomponent [(childField)]="selection"></subchildcomponent>
    

    注意:子childcomponent aloso必须像mecomponent一样实现双向绑定。

    我创建了一个例子,看起来这是一个常见的问题: https://stackblitz.com/edit/angular-2-way-binding?embed=1&file=src/app/app.component.html