Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular2 change @input value in child component then change this value in parent component not work

parent component class

export class Parent {
   show: boolean = false;
   constructor() { }
   showChild() {
      this.show = true;
   }
}

parent component template

<child [isShow]="show"></child>

child component class

export class Child {
   @Input isShow: boolean = false;
   constructor() { }
   onClick() {
      this.isShow = false;
    }
}

after I triggered onClick() in child component, the showChild() would not work to show the child component.

why?

like image 705
NieWei Avatar asked Apr 12 '17 14:04

NieWei


People also ask

How do you find the value of a child component in the parent component?

We can get child component values in the parent component by creating a reference to the child component using the @ref directive in the Parent component. Using the reference instance, you can access the child component values in the parent.


1 Answers

The value is being passed exclusively from parent to child because you're using square brackets.

In order for the value to go both ways, you need to use a two-way data binding.

That means your isShow attribute should be like:

@Input()  isShow: boolean;
@Output() isShowChange = new EventEmitter<boolean>();

And the template should be

<child [(isShow)]="show"></child>

or

<child [isShow]="show" (isShowChange)="show = $event"></child>

Take a look at the two-way data binding tutorial page:

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

like image 198
Pedro Penna Avatar answered Sep 29 '22 21:09

Pedro Penna