user3497437 user3497437 - 1 month ago 13
TypeScript Question

How to apply @ViewChildren in angular2 for communication between Parent and child

i am trying to understand @ViewChildren() decorator. I created a Component called Component-A that accepts a user email address. Created the parent component called "component-B" that has twins( 2 Component-A's). Now i found online tutorials on how parent and child components can interract by incorporating Event and property binding by using @Input() and @Output() decorator. But how can one achieve the same result using @ViewChildren() where we check if both emails entered are the same and print out they match?

@Component({
selector: 'component-A'
styleUrls: [],
templateUrl: `<form>
<div>
<fieldset>
<legend>Component A</legend>
<div class="form-horizontal">
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input type="email" class="form-control" id="inputEmail3" placeholder="Email">
</div>
</div>
</fieldset>
})

export class ComponentA {

}


Now i have a componentB:

@Component({
selector: 'component-B',
styleUrls: [],
templateUrl: `
<form>
<div>
<fieldset>
<legend>Parent Component</legend>
<div class="form-horizontal">
<div class="form-group">
<label for="1" class="col-sm-2 control-label">1</label>
<div class="col-sm-10">
<component-A></component-A>
</div>

<div class="form-group">
<label for="2" class="col-sm-2 control-label">2</label>
<div class="col-sm-10">
<component-A></component-A>
</div>
</div>
</div>
</fieldset>
</div>
</form>
})

export class Parent {
}

Answer
export class Parent {
  @ViewChild(ComponentA) componentA:ComponentA;

  ngAfterViewInit() {
    console.log(this.componentA);
  }
}

For more details see http://stackoverflow.com/a/35209681/217408