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

bi directional binding with variable instead of using emitter?

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

我正在查看 Output 和 EventEmitter,但那是在创建新的变量,这些变量仅被监视以执行以下函数:

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

然后您可以将其引用为:

(clicked)="myFunc(id)"

鉴于我的用例,我认为不需要输出,因为我没有执行父等中定义的函数,只是想更新 属性、myItem在这种情况下。

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

我正在添加一些示例代码。

组件 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 有一个选择 属性,但它从未在其中分配,它实际上只是将它传递到更高的级别,所以由于它没有在代码中设置,我不能说:selectionChange.emit(this.selection);。鉴于一些答案,我如何解决这个概念?它会自动传递,还是我必须创建某种 StreamListener 来监视变量变化?

([clicked])这样的双向数据绑定只在组件内部有效。由于您的要求是在父组件和子组件之间进行通信,因此您需要一些能让父组件或子组件知道其他组件发生了变化的东西。

此外,双向数据绑定主要用于从视图到模型的通信(显然根据 angular 1.x.x),它并不意味着从父组件到子组件的通信并且不同于 angular 1.x.x 和 angular +2.x.x

在您的情况下,您可以使用 EventEmitor by @OutputRxJs Subject.

希望它能回答您的问题

对于双向绑定你应该遵循这个模式,注意事件名称应该是你的输入名称+ Change,然后双向绑定工作,在你的组件中当你改变 [=14= 的值时] 发出变化事件。

@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---

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>();

必须通过在 @Input 名称中添加 propertyNameChange 来命名 @Output。 你可以在父-子-子子中使用它来交换数据。 父组件

<mycomponent [(selection)]="fieldInParentComponent"></mycomponent>

我的组件

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

注意:子子组件也必须像 mecomponent 一样实现双向绑定。

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