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



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

我正在查看输出和事件发射器,但这正在创建新的变量,这些变量仅被监控以执行以下功能:

@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 来监视变量更改?

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

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

用法

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

框中的香蕉语法只是一个语法糖,如下所示

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

请注意,这是为了Components而不是Services

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

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

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

在您的情况下,您可以通过@OutputRxJsSubject来使用EventEmitor

希望它能回答你的问题

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

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

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

我的组件

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

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

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

最新更新