简体   繁体   中英

Angular - Passing one component as parameter to another

In a dummy Angular application I have two components: counter and test01 . As you can see on the repository file

This GitHub repository contains a totally working example.

Please, check this image.

这个图片。

If you click the button: "Change Counter Value" it sets the counter number to: 8 successfully.

But my question is: how could I pass the counter component to the test01 component to change the value from inside a test01 method in an easier way?

Right now the logic of the component: test01 is more difficult as you can see here

I would like to do something like:

test01_obj.counter = 8;

with no too much code more.

Any idea on this?

You are approaching the problem in the wrong way.

I suggest you to share the model (the count) between the two components instead and rely on bindings to achieve [indirect] interaction.

ie:

 export class ContainerComponent {

   myCounterModel: CounterModel = {
       count: 0
   };
   ...
 }

export class CounterComponent {
    ...
    @Input()
    counter: CounterModel;
}

export class Test01Component {
    ...
    @Input()
    counter: CounterModel;
}


  //ContainerComponent template

<counter [(counter)]="myCounterModel"></counter>
<hr />
<test01 [(counter)]="myCounterModel" [resetValue]="8"></test01>

Makes sense?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM