如何以编程方式更改已呈现的组件的输入值(Angular 2)(How to programatically change the input value of a component which wa

编程入门 行业动态 更新时间:2024-10-24 14:17:50
如何以编程方式更改已呈现的组件的输入值(Angular 2)(How to programatically change the input value of a component which was already rendered (Angular 2))

在我的Angular 2应用程序中,我有一个组件(mainComp),其中包含另一个via

<my-comp></my-comp>

my-comp通过发出(在选择/点击时)它的值(它是一个自定义下拉列表)

this.optionSelected.emit(currentOption == "Not described" ? null : currentOption);

mainComp接收下拉列表的值

In my Angular 2 app I have a component (mainComp) which includes another one via

<my-comp></my-comp>

my-comp emits (on select / click) it's value (it's a custom dropdown) via

this.optionSelected.emit(currentOption == "Not described" ? null : currentOption);

mainComp receives the value of the dropdown by

最满意答案

你有一个双向绑定,所以如果对象发生了变化,结果也应该刷新。 如果你有一个EventEmitter,请在构造函数中订阅,如:

class MainComp { let value; ... constructor(private myComp : MyComp) { myComp.optionSelected.subscribe{ (value) => this. value = value; } }

现在,每次EventEmitter触发时,MainComp中的value-attribute都会更新。

如果你想要一些简洁的东西,请看一下ngOnChanges( https://angular.io/docs/ts/latest/cookbook/component-communication.html )

更新 :你的意思是...... 喜欢这个:

class MainComp { template: `<myComp [(value)]=value></myComp>` ... } class MyComp { @Input(): value; ... }

这应该创建一个双向绑定,因此如果其中一个组件编辑值,则另一个得到通知。 看看这个: https : //angular.io/docs/ts/latest/guide/template-syntax.html#!#ngModel

You've got a 2-way-binding, so if the object changes, the result should also be refreshed. If you've got an EventEmitter, subscribe in the constructor like:

class MainComp { let value; ... constructor(private myComp : MyComp) { myComp.optionSelected.subscribe{ (value) => this. value = value; } }

Now, everytime the EventEmitter fires emit, the value-attribute in MainComp will be updated.

If you want to something facy, take a look at ngOnChanges (https://angular.io/docs/ts/latest/cookbook/component-communication.html)

Update: Do you mean sth. like this:

class MainComp { template: `<myComp [(value)]=value></myComp>` ... } class MyComp { @Input(): value; ... }

This should create a 2-way-binding, so if one of the Components edits value, the other gets notified. Take a look at this: https://angular.io/docs/ts/latest/guide/template-syntax.html#!#ngModel

更多推荐

mainComp,my-comp>,<my-comp><,电脑培训,计算机培训,IT培训"/> <meta

本文发布于:2023-08-03 18:53:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1396274.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组件   方式   Angular   programatically   rendered

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!